我想使用 vba 在 Excel 中创建一个具有动态数量列的图表。 我当前的部分代码是:
'Create chart
'Columns("A:DZ").Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatterLinesNoMarkers).Select
ActiveChart.SetSourceData Source:=Range("Graphs!$A:$AL")
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
但是,该图包括列
A
到 AL
。然而,AL
并不是我的最后一篇专栏。我希望我的图表包含 A
直到 lastcolumn-1
列。
然后我想创建另一个仅包含 A 列和最后一列的图表。
我不确定如何适应当前的代码。我尝试了Range("Graphs!$A"&(lastcol-1)
,但这显然不起作用。 lastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
已经在我的代码中创建,因此已经可以工作了。
如果有不清楚的地方,请告诉我。
Dim lastCol As Long
Dim chartRange As Range
' Get the last column in the "Graphs" sheet
lastCol = Sheets("Graphs").Cells(1, Columns.Count).End(xlToLeft).Column
' Set the range for the first chart (A to the second-last column)
Set chartRange = Sheets("Graphs").Range(Cells(1, 1), Cells(1, lastCol - 1)).Resize(Cells(Rows.Count, lastCol - 1).End(xlUp).Row)
' Create the first chart
ActiveChart.SetSourceData Source:=chartRange
' Do the rest of your code
' Your second chart
' Set the range to include only columns A and the last column
Set chartRange = Union(Sheets("Graphs").Range("A1:A" & Sheets("Graphs").Cells(Rows.Count, 1).End(xlUp).Row), _
Sheets("Graphs").Range(Cells(1, lastCol), Cells(Rows.Count, lastCol).End(xlUp)))
' Do the rest of your code