在 VBA 中选择两列并创建图表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20265708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting Two Columns and creating a chart in VBA
提问by user3045746
Hi I am pretty new to VBA. I am trying to create a chart with values from Two columns A1:A10, C1:C10 (i.e. A and C).I selected these two columns with mouse and when i try the macro code i am getting the following error " Run-time error 1004, Application error or Object defined error". But i am able to create chart when i select columns A and B (i.e. A1:B10). Need some suggestion.
嗨,我是 VBA 的新手。我正在尝试使用两列 A1:A10、C1:C10(即 A 和 C)中的值创建图表。我用鼠标选择了这两列,当我尝试宏代码时,出现以下错误“运行时错误 1004,应用程序错误或对象定义错误”。但是当我选择 A 列和 B 列(即 A1:B10)时,我可以创建图表。需要一些建议。
This is my code:
这是我的代码:
Sub Chart()
Dim rng As Range
Set rng = Selection
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=rng
ActiveChart.ChartType = xlColumnClustered
End Sub
回答by Siddharth Rout
This works for me
这对我有用
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
Or if you still want to use .Selection
then use this
或者,如果您仍想使用,请.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