使用 vba 创建 Excel 列直到 LastCol 的图表

问题描述 投票:0回答:1

我想使用 VBA 在 Excel 中创建一个图表,其中包含 A 列直到最后一列。 最后一列由以下行确定:

        Dim lastCol As Long, lastColLetter As String
        lastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
        lastColLetter = Split(Cells(1, Columns.Count).End(xlToLeft).Address, "$")(1)
        lastColLetter = Chr(34) & lastColLetter & Chr(34)

lastColLetter
打印例如
"AL"

创建图表时,我有以下代码:

  ActiveSheet.Shapes.AddChart2(240, xlXYScatterLinesNoMarkers).Select
  ActiveChart.SetSourceData Source:=Range("Graphs!$A:$DZ")
  ActiveChart.ChartTitle.Select
  ActiveChart.ChartTitle.Text = "Pressure over time"

  With ActiveChart
    With .Axes(xlCategory, xlPrimary)
      .HasTitle = True
      .AxisTitle.Text = "Foaming time [s]"
      .MaximumScale = 120
    End With
    With .Axes(xlValue, xlPrimary)
      .HasTitle = True
      .AxisTitle.Text = "Pressure [bar]"
    End With
    .HasLegend = False
  End With

我想用

DZ
之类的东西替换
ActiveChart.SetSourceData Source:=Range("Graphs!$A:$DZ")
ActiveChart.SetSourceData Source:=Range("Graphs!$A:$" & lastColLetter)
,这似乎不起作用。它会产生一个空图。创建图表时如何使用lastCol?

excel vba graph scatter-plot
1个回答
0
投票

如果您正在为 Excel 进行 VBA 编程并且想要了解列的字符,则几乎可以 100% 确定您做错了事情。

此外,如果您使用带有

Active
的东西(就像您的情况
ActiveChart
),代码至少有一种气味。在我看来,它是用宏记录器创建的 - 这因创建错误代码而臭名昭著。

有不止一种方法可以做你想做的事,但以下可以给你一个想法:

Dim lastCol As Long
With ThisWorkbook.Worksheets("Graphs")
    lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With

Dim sh As Shape
Set sh = ActiveSheet.Shapes.AddChart2(240, xlXYScatterLinesNoMarkers)
With sh.Chart
    .SetSourceData Source:=Cells(1, 1).Resize(, lastCol).EntireRow
    .ChartTitle.Select
    .ChartTitle.Text = "Pressure over time"

    With .Axes(xlCategory, xlPrimary)
        .HasTitle = True
        .AxisTitle.Text = "Foaming time [s]"
        .MaximumScale = 120
    End With

    With .Axes(xlValue, xlPrimary)
        .HasTitle = True
        .AxisTitle.Text = "Pressure [bar]"
    End With
    .HasLegend = False
End With
© www.soinside.com 2019 - 2024. All rights reserved.