Excel VBA - 调整 ChartArea 的大小以适应范围

Excel VBA - resize ChartArea to fit range

我正在尝试调整图表大小以适应特定范围的单元格。问题是它没有将图表大小精确设置为范围大小。下面是一个随机图表来演示这个问题。为了便于理解,我突出显示了范围:黄色 - 适合 ChartArea,蓝色 - 适合 PlotArea。可以看出,ChartArea 超出了范围,在右侧和底部,这随后导致 PlotArea 移位(PlotArea 的大小看起来不错,只是位置不正确)

下面是我试过的代码:

Sub xyz()

Dim chrt As Chart
Dim rngCA As Range
Dim rngPA As Range

Set chrt = ChartObjects("Chart 1").Chart
Set rngCA = Range("C5:I16")
Set rngPA = Range("E7:H14")

    With chrt.ChartArea
        .Height = rngCA.Height
        .Width = rngCA.Width
        .Top = rngCA.Top
        .Left = rngCA.Left
    End With

    With chrt.PlotArea
        .InsideHeight = rngPA.Height
        .InsideWidth = rngPA.Width
        .InsideTop = rngPA.Top - rngCA.Top
        .InsideLeft = rngPA.Left - rngCA.Left
    End With

End Sub

如有任何帮助,我们将不胜感激

尝试为 ChartObject 而不是 ChartArea 设置属性...

With chrt.Parent 'refers to chartobject
    .Height = rngCA.Height
    .Width = rngCA.Width
    .Top = rngCA.Top
    .Left = rngCA.Left
End With

With ChartObjects("Chart 1")
    .Height = rngCA.Height
    .Width = rngCA.Width
    .Top = rngCA.Top
    .Left = rngCA.Left
End With