VBA 中的命令charts.add将一个新的图表对象添加到工作簿。我认为F11在 Excel 中点击确实是一样的。
问题是,此命令使用当时选定的工作表和单元格周围的数据来填充图表。如果没有数据或没有可用数据,则返回一个空图表。
我的问题是:“我怎样才能强制命令提供一个空图表?” . 之后我打算用 VBA 代码填充图表。
这个问题的一个简单答案是创建一个新的空工作表并选择该工作表上的单元格 A1,然后创建一个新图表,但这是一个相当丑陋的解决方案。任何有关优雅解决方案的帮助将不胜感激。
尝试添加额外的行,这将在图表出现后立即删除数据:
Charts.Add
ActiveChart.ChartArea.Clear
编辑替代解决方案,但这将跳回数据表:
'select last cell in the sheet which is usually empty
Dim tmpSel As Range
Set tmpSel = Selection
Cells(Rows.Count, Columns.Count).Select
'add chart
Charts.Add
'back to base sheet and select range previously selected
tmpSel.Parent.Activate
tmpSel.Select
我遇到过同样的问题。我尝试使用该ActiveChart.ChartArea.Clear属性并导致崩溃。然后我在添加图表后尝试ActiveChart.ChartArea.ClearContents,它给了我想要的结果,这是一个我可以添加系列的空白图表。
我刚刚花了很长时间来解决这个问题。不管我做什么,该死的 excel 从某个地方获取了一些数据,这真的很烦人。.ChartArea.Clear 方法在我之后操作图表时导致崩溃(甚至填充了新系列)
这是我从一个真正的工作项目中得到的最终解决方案(一个片段,对一些用户特定的变量感到抱歉)
Dim Chrt as Chart
' This is "the elegant" method
' Parameters of Add do not actually matter, we will specify all details later
Set Chrt = MySheet.ChartObjects.Add(0, 0, 100, 100).Chart
' And here we start to fill the empty (!) Chart with some useful series... :)
With Chrt
' Specifying chart type
.ChartType = xlXYScatterLinesNoMarkers
' Positioning (Page is a range - fragment of my code)
With .Parent
.Top = Page(3, 1).Top
.Left = Page(3, 1).Left
.Width = Page.Width
.Height = (Page.Height - (Page(4, 1).Top - Page(1, 1).Top)) ' / 2
End With
' Adding a new serie
With .SeriesCollection.NewSeries
.Name = "D" & Work.Cells(iFileRow, 2)
.XValues = Range(MySheet.Cells(2, 1), MySheet.Cells(DataEnd, 1))
.Values = Range(MySheet.Cells(2, 10), MySheet.Cells(DataEnd, 10))
.MarkerStyle = -4142
' Formating the series
With .Format.Line
...
Excel 尝试使用所选数据或包含活动单元格的数据块填充全新的图表。
选择未使用范围中间的空白单元格。如果没有要绘制的数据,Excel 将插入一个空白图表。
我喜欢这个ActiveChart.ChartArea.Clear答案。
当我在 excel 2003 中执行宏时,我一直在执行以下操作。它将手动删除所选图表中的所有系列。
Charts.Add
ActiveChart.ChartType = xlXYScatterLinesNoMarkers
ActiveChart.Location Where:=xlLocationAsNewSheet
' manually delete every series that may be in a new chart
On Error GoTo 30
yy = ActiveChart.SeriesCollection.Count
For xx = yy To 1 Step -1
ActiveChart.SeriesCollection(xx).Delete
30 Next xx