I have recently migrated to Excel 2016 from 2010 and one of the sheets I inherited from a colleague has stopped working. I am in the process of learning VBA but would appreciate help with the run-time error that I keep getting when running the below code.
I believe it results from the way variables are declared (or seemingly not in this case). The function takes in a range which overlays a chart. It then exports the chart as a .png image. Another thing I don't understand is why it works fine in Excel 2010 but not 2016?
Error 424 - Object Required:
With .Pictures(1)
The code:
Sub createPNG(sheetName As String, rangeName As String, fileName As String)
Dim vFilePath As Variant
Dim rSelection As Range
Dim sDefaultName As String
Sheets(sheetName).Range(rangeName).Select
Set rSelection = Selection
vFilePath = "Z:\marginsOutput\Charts\" & fileName & ".png"
'-- copy selected range as picture (not as bitmap)
rSelection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
'--Create an empty chart, slightly larger than exact size of range copied
With Sheets(sheetName).ChartObjects.Add( _
Left:=rSelection.Left, Top:=rSelection.Top, _
Width:=rSelection.Width + 2, Height:=rSelection.Height + 2)
With .Chart
' clean up chart
.ChartArea.Format.Line.Visible = msoFalse
' paste and position picture
.Paste
With .Pictures(1)
.Left = .Left + 2
.Top = .Top + 2
End With
' export
.Export CStr(vFilePath)
End With
' remove no-longer-needed chart
.Delete
End With
End Sub