这对我有用
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