VBA Excel:带有dynamic范围的macros创build图

我正在尝试创build一个macros,其中创build一个图表的dynamic范围的列。 这是我迄今为止。

Private Sub CommandButton2_Click() With Sheets("Sheet1") Charts.Add ActiveChart.ChartType = xlColumnClustered ActiveChart.SetSourceData Source:=.Range("D2", Cells(2, N + 3)) ActiveChart.Location xlLocationAsObject End With End Sub 

但是现在我一直遇到运行时错误,

“指定的维度对当前图表types无效”

当我查看代码时,它会一直引用最后一行。

 ActiveChart.Location xlLocationAsObject 

有任何想法吗? 谢谢

跟进

这里是引用N的代码

 Dim N As Long Private Sub CommandButton1_Click() Dim x As Integer Dim y As Integer x = 0 y = 1 N = Application.InputBox(Prompt:="Enter value", Type:=1) If N > Columns.Count Then N = Columns.Count Else For i = 4 To 9999 Cells(1, i).ClearContents Cells(3, i).ClearContents Next i End If For i = 4 To N + 3 x = x + y Cells(1, i) = x Next i End Sub 

xlLocationAsObject需要where参数,指定要将图表对象embedded或放置的位置

更换

 ActiveChart.Location xlLocationAsObject 

 ActiveChart.Location xlLocationAsObject, Name 

将图表embedded到Sheet1

查看所有可用的选项 在这里输入图像说明