The point of this code is to create a chart in a new worksheet, which it does. After this, when I click the button to generate the chart again in a new worksheet named the same, it's supposed to delete that sheet and create a new generated chart.
It creates the chart but when I go back to click the button, it generates the chart in the sheet where the button is and throws the error 91: Object variable or With block variable not set.
Debugging points me to the following line:
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"
Below is the code:
Sub HistoricalDemand()
' Creates a line chart for the demand column
For Each ws In Worksheets
If ws.Name = "Demand Line Chart" Then
Application.DisplayAlerts = False
Sheets("Demand Line Chart").Delete
Application.DisplayAlerts = True
Exit For
End If
Next
Columns("A:A").Select
Selection.NumberFormat = "[$-en-US]mmm-yy;@"
Range("A:A,E:E").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
' Try With command here
ActiveChart.SetSourceData Source:=Range("A:A,E:E")
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"
' Places line chart in a new worksheet called Demand Line Chart
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.Orientation = 70
Selection.MajorTickMark = xlNone
With ActiveChart
.Axes(xlCategory).Select
.Axes(xlCategory).MajorUnit = 2
.ChartTitle.Select
.ChartTitle.Text = "Historical Demand"
.SetElement (msoElementLegendRight)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Historical Demand"
With Selection.Format.TextFrame2.TextRange.Characters(1, 17).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
ActiveChart.ChartArea.Select
End With
End Sub