【发布时间】:2020-02-08 09:02:22
【问题描述】:
这段代码的重点是在一个新的工作表中创建一个图表,它确实如此。在此之后,当我单击按钮在一个名为相同的新工作表中再次生成图表时,它应该删除该工作表并创建一个新的生成图表。
它会创建图表,但是当我返回单击按钮时,它会在按钮所在的工作表中生成图表并抛出错误 91:对象变量或未设置块变量。
调试将我指向以下行:
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"
下面是代码:
Sub HistoricalDemand()
' Creates a line chart for the demand column
For Each ws In Worksheets
If ws.Name = "Demand Line Chart" Then
Application.DisplayAlerts = False
Sheets("Demand Line Chart").Delete
Application.DisplayAlerts = True
Exit For
End If
Next
Columns("A:A").Select
Selection.NumberFormat = "[$-en-US]mmm-yy;@"
Range("A:A,E:E").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
' Try With command here
ActiveChart.SetSourceData Source:=Range("A:A,E:E")
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"
' Places line chart in a new worksheet called Demand Line Chart
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.Orientation = 70
Selection.MajorTickMark = xlNone
With ActiveChart
.Axes(xlCategory).Select
.Axes(xlCategory).MajorUnit = 2
.ChartTitle.Select
.ChartTitle.Text = "Historical Demand"
.SetElement (msoElementLegendRight)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Historical Demand"
With Selection.Format.TextFrame2.TextRange.Characters(1, 17).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
ActiveChart.ChartArea.Select
End With
End Sub
【问题讨论】:
-
图表应该在哪个表(名称)中创建?一张新表?保存图表源数据的工作表的名称是什么?
-
@RicardoDiaz 应该在其中创建图表的工作表名称是一个名为“需求线图”的新工作表。保存图表源数据的工作表的名称称为“DATA”。这是电子表格的图片:imgur.com/a/8WWPxNQ
-
看到您以前的问题有很好的答案,但没有标记它们。如果他们解决了您的问题,请记住检查每个答案左侧的标记,以便其他人可以找到他们。
-
@RicardoDiaz 完成,感谢您的留言。
标签: excel vba excel-charts