调整嵌入图表对象中的绘图区域大小

时间:2017-03-08 13:29:40

标签: excel-vba vba excel

我在Excel中的嵌入式图表中调整绘图区域的大小有问题

Dim myChart As Chart

maxPie = ThisWorkbook.Sheets(sheetName).Range("A1048576").End(xlUp).Row

Set myChart = ThisWorkbook.Sheets(sheetName).Shapes.AddChart.Chart


myChart.ChartType = xlBarClustered
myChart.SetSourceData Source:=Range(sheetName & "!$A$5:$C$" & maxPie)

With myChart.Parent
    .Top = 10
    .Left = 500
    .Width = 500
    .Height = 500
End With

With myChart.PlotArea
    .Top = 70
    .Height = 420
End With

如果我按调试然后按F5然后它调整它的大小,我是否需要在我的代码中添加延迟,因为它在我尝试调整它之前没有完成生成绘图区域

2 个答案:

答案 0 :(得分:1)

Rory关于阅读价值的评论解决了这个问题,奇怪的是,这是需要的..

Dim temp As Integer
With myChart.PlotArea
    temp = .Top
    temp = .Height
    .Top = 70
    .Height = 420
End With

答案 1 :(得分:0)

我认为你的代码返回错误的原因是因为PlotArea属性只能在Chart对象完全加载后才能修改。所以,是的,您需要完成图表对象加载过程并修改任何PlotArea属性。 下面的代码将起作用。试试吧..!

Option Explicit

Public Sub Demo()

    Dim maxPie As Long
    Dim myChart As Chart

    'I assume that your chart is on Sheet1
    maxPie = Sheet1.Range("A1048576").End(xlUp).Row
    Set myChart = Sheet1.Shapes.AddChart2.Chart

    With myChart
        .ChartType = xlBarClustered
        .SetSourceData Source:=Range("Sheet1!$B$2:$C$" & maxPie)
    End With

    With myChart.Parent
        .Top = 10
        .Left = 500
        .Width = 500
        .Height = 500
    End With

    'Delay the SetPlotArea code execution using OnTime function
    Application.OnTime Now, "SetPlotArea", Now + TimeValue("0:0:5")

End Sub

Public Sub SetPlotArea()
    Dim ch As Chart
    Set ch = Sheet1.ChartObjects(1).Chart

    ch.PlotArea.Top = 70
    ch.PlotArea.Height = 420
End Sub