目的是针对column A
(X轴)绘制值。用户在单元格G4
中选择一个列名,G4
的值可以是B
,C
,C
,D
。根据列名,必须绘制一个图表。
我能够编写以下代码来选择数据,但无法动态选择数据。
Sub Chart()
Dim Lastrow As Long
Dim TimeAxis As Range
Dim Values As Range
Dim cht As Object
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
TimeAxis = Range("A1:A" & Lastrow).Select '<----- X Axis (Static)
Values = Range("B1:B" & Lastrow).Select '<----- User selected as per cell G4 (Dynamic)
'Plot TimeAxis Vs Values
Set cht = ActiveSheet.Shapes.AddChart2
cht.Chart.SetSourceData Source:=rng '<------ User Range (Dynamic)
cht.Chart.ChartType = xlXYScatterLines
End Sub
答案 0 :(得分:0)
请注意,行计数变量的类型必须为Long
,因为Excel的行数多于Integer
不能处理的行:Dim Lastrow As Long
。我建议在VBA中使用always to use Long instead of Integer,因为Integer
根本没有任何好处。
您必须使用Set TimeAxis
(因为范围是对象)并删除.Select
。另见
How to avoid using Select in Excel VBA。
最后Set
您的rng
否则为空,因此您无法在Source:=rng
中使用它。
因此,您最终得到的像是:
Option Explicit
Sub GenerateChart() 'dont use "chart" as procedure name it is a type in VBA and therefore a reserved word
Dim LastRow As Long
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
Dim TimeAxis As Range
Set TimeAxis = Range("A2:A" & LastRow) 'X Axis values start at A2!!!
Dim SelCol As String
SelCol = ActiveSheet.Range("G4") 'read column name from G4
Dim Values As Range
Set Values = Range(SelCol & "1:" & SelCol & LastRow) '<----- User selected as per cell G4 (Dynamic)
'Plot TimeAxis Vs Values
Dim cht As Object
Set cht = ActiveSheet.Shapes.AddChart2
cht.Chart.SetSourceData Source:=Values '<------ User Range (Dynamic)
cht.Chart.FullSeriesCollection(1).XValues = TimeAxis 'x axis values
cht.Chart.ChartType = xlXYScatterLines
End Sub