VBA Excel:宏创建的具有动态范围的图形

VBA Excel:宏创建的具有动态范围的图形,vba,excel,Vba,Excel,我试图创建一个宏,其中创建的图形具有列的动态范围。这是我到目前为止所拥有的 Private Sub CommandButton2_Click() With Sheets("Sheet1") Charts.Add ActiveChart.ChartType = xlColumnClustered ActiveChart.SetSourceData Source:=.Range("D2", Cells(2, N + 3)) ActiveChart.Location

我试图创建一个宏,其中创建的图形具有列的动态范围。这是我到目前为止所拥有的

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
但是现在,我在语句中不断遇到运行时错误-

“指定的维度对于当前图表类型无效”

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

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
需要
where
参数,指定要将图表对象嵌入或放置的位置

替换

ActiveChart.Location xlLocationAsObject 

将图表嵌入
Sheet1

查看所有可用选项

什么是N?“你打算绘制多大范围的数据?”Thinkingcap说。修改了问题
ActiveChart.Location xlLocationAsObject, Name