I want to create a graph in Excel using VBA that contains column A up till the last column. The last column is determined with the line:
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)
This lastColLetter prints for example "AL"
When creating a graph, I have the following code:
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
I want to replace the DZ line ActiveChart.SetSourceData Source:=Range("Graphs!$A:$DZ") with something like ActiveChart.SetSourceData Source:=Range("Graphs!$A:$" & lastColLetter), which does not seem to work. It results in an empty graph. How can I use lastCol while creating a graph?
Cellsto get the cell reference - two of these stuck together create a range. No need to figure out the column letter. You could useRange(Cells(1, 1).EntireColumn, Cells(5, ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column).EntireColumn)lastColLetter = Chr(34) & lastColLetter & Chr(34). lastColLetter is already a string