1

嗨,我对 VBA 很陌生。我正在尝试使用两列 A1:A10、C1:C10(即 A 和 C)中的值创建一个图表。我用鼠标选择了这两列,当我尝试宏代码时,我收到以下错误“运行时错误 1004,应用程序错误或对象定义错误”。但是当我选择 A 列和 B 列(即 A1:B10)时,我能够创建图表。需要一些建议。

这是我的代码:

Sub Chart()

    Dim rng As Range

    Set rng = Selection

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=rng
    ActiveChart.ChartType = xlColumnClustered

End Sub
4

1 回答 1

0

这对我有用

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim objChrt As ChartObject
    Dim chrt As Chart

    Set ws = ThisWorkbook.Sheets("Sheet1")
    With ws
        Set rng = .Range("A1:A10,C1:C10")
        .Shapes.AddChart
        Set objChrt = .ChartObjects(.ChartObjects.count)
        Set chrt = objChrt.Chart

        With chrt
            .ChartType = xlColumnClustered
            .SetSourceData Source:=rng
        End With
    End With
End Sub

或者,如果您仍想使用,请.Selection使用此

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim objChrt As ChartObject
    Dim chrt As Chart

    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first."
        Exit Sub
    End If

    Set ws = ThisWorkbook.Sheets(Selection.Parent.Name)
    With ws
        Set rng = Selection
        .Shapes.AddChart
        Set objChrt = .ChartObjects(.ChartObjects.count)
        Set chrt = objChrt.Chart

        With chrt
            .ChartType = xlColumnClustered
            .SetSourceData Source:=rng
        End With
    End With
End Sub
于 2013-11-28T12:24:56.307 回答