I am trying to use a bit of VBA to copy a range of cells as an image to paste into a non-Microsoft program. The code below works on occasion but errors out 90% of the time on "sh.Copy". It appears as though it isn't always picking up my range of cells and defining them as "sh".
What am I missing?
What am I missing?
VBA Code:
'create jpg for selected range
'==================================================
Dim tmpChart As Chart, n As Long, shCount As Long, sht As Worksheet, sh As Shape
Dim fileSaveName As Variant, pic As Variant
'Sets the Excel Copy Range
FCF.Range("B1:G" & (FCF.Range("B3").End(xlDown).Row)).SpecialCells(xlCellTypeVisible).Select
'Create temporary chart as canvas
Set sht = Selection.Worksheet
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
'Selection Copy
sht.Pictures.Paste.Select
Set sh = sht.Shapes(sht.Shapes.Count)
Set tmpChart = Charts.Add
tmpChart.ChartArea.Clear
tmpChart.Name = "PicChart" & (Rnd() * 10000)
Set tmpChart = tmpChart.Location(Where:=xlLocationAsObject, Name:=sht.Name)
tmpChart.ChartArea.Width = sh.Width
tmpChart.ChartArea.Height = sh.Height
tmpChart.Parent.Border.LineStyle = 0
'Paste range as image to chart
sh.Copy
tmpChart.ChartArea.Select
tmpChart.Paste
'Create folder location
myfoldername = Environ("userprofile") & "\Desktop\Facility Care Forms"
'create file name
myfilename = Sheets("Facility Care Form").Range("B2 ").Text & _
Format(Now(), " mmm-dd-yyyy hhmmss") & ".jpg"
'Check to see if folder name exists already. If not, create it
If Dir(myfoldername, vbDirectory) = "" Then MkDir myfoldername
'Save file
fileSaveName = myfoldername & "\" & myfilename
'Save chart image to file
If fileSaveName <> False Then
tmpChart.Export Filename:=fileSaveName, FilterName:="jpg"
End If
'Clean up
sht.Cells(1, 1).Activate
sht.ChartObjects(sht.ChartObjects.Count).Delete
sh.Delete