根据动态用户范围绘制图表

To plot chart based on dynamic user ranges

目的是根据 column A(X 轴)绘制值。用户 select 在单元格 G4 中输入列名,G4 的值可以是 BCCD.必须根据列名称绘制图表。

我能够编写以下代码 select 数据,但我不能 select 动态数据。

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

请注意,行计数变量必须是 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