首页 > 解决方案 > 为什么我的 VBA 代码只有在添加 MsgBox 时才有效?

问题描述

编辑:我相信我的错误消息“每个图表的最大数据系列数为 255”与我在调用 AddChart2 方法之前的范围选择有关。我仍然不知道为什么它之前说我的图表没有标题,即使我声明 .HasTitle 是真的。考虑一下这个问题现在已经解决,尽管我仍然想知道为什么它以前不起作用。

同样在我使用的实际子例程中,预先存在的图表对象在到​​达此代码之前被删除,因此 ChartObjects(1) 索引没有问题。

下面代码的成功与否,完全取决于我是否包含 MsgBox 函数。此外,仅当我将此特定参数传递给 MsgBox 时,它似乎才有效(即使页面上有一个 ChartObject,键入“MsgBox 1”也不起作用)。有人知道为什么是这样吗?

ActiveSheet.Shapes.AddChart2(227, xlLine).Select
ActiveChart.SetSourceData Source:=Range("$M2:$M" & CStr(Cells(Rows.Count, 13).End(xlUp).Row))

'MsgBox ActiveSheet.ChartObjects.Count

With Sheets("blah").ChartObjects(1).Chart
    .HasTitle = True
End With

MsgBox Sheets("blah").ChartObjects(1).Chart.HasTitle   ' (always returns True)

Sheets("blah").ChartObjects(1).Chart.ChartTitle.Text = "bleh"

当代码工作时,我会得到一个带有预期标题的图表。当它不起作用时,我会收到一条错误消息,指出图表没有标题。

标签: excelvba

解决方案


假设 ActiveSheet 是Sheet("blah"),试试这个......

Dim theChart As ChartObject ' Reference the new or existing chart
Dim sourceRange As Range    ' Chart's data source

' Create or attach to the chart and get the chart's source data range
With Sheets("blah")

    ' Create the chart if it doesn't exist
    If .ChartObjects.Count = 0 Then
        .Shapes.AddChart2 227, xlLine
    End If

    ' Grab a pointer to the chart
    Set theChart = .ChartObjects(1)

    ' Grab a pointer to the source range while inside the sheet's WITH block
    Set sourceRange = .Range("$M2:$M" & CStr(.Cells(.Rows.Count, 13).End(xlUp).Row))

End With

' Set the chart up.
With theChart.Chart
    .SetSourceData source:=sourceRange
    .HasTitle = True
    .ChartTitle.Text = "bleh"
End With

' Clean up
Set theChart = Nothing
Set sourceRange = Nothing

编辑:原始代码在我测试时出错。这已经在 Excel 2016 中进行了测试并且有效。还为代码添加了注释以进行澄清。


推荐阅读