excel - 为什么我的 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"
当代码工作时,我会得到一个带有预期标题的图表。当它不起作用时,我会收到一条错误消息,指出图表没有标题。
解决方案
假设 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 中进行了测试并且有效。还为代码添加了注释以进行澄清。
推荐阅读
- ionic-framework - 对 ionic 中的 FCM 和 Push 插件感到困惑
- c++ - 如何将类方法设置为参数并将它们与 Visual Studio 2017 上的 lambdas 一起使用?
- prisma - 为什么 prisma 在创建新记录时会出现内部错误?
- postgresql - PostgreSQL 中缺少一些 .dll 文件
- javascript - 语法错误 node_modules / esnext 中的意外令牌导出和 commonjs 不兼容
- c# - 子域的 Asp net core cookie 身份验证
- woocommerce - 将 url 添加到 woocommerce 购物车
- java - Selenium 测试 - 通过弹出窗口添加的文本未保存
- node.js - 节点/mongoDB 遇到问题
- scala - 无法将 spark DF 写为 parquert 文件错误:java.lang.NoSuchMethodError: org.json4s.jackson.JsonMethods