VBA Convert Excel range to JPG Image

How to convert a range of Cell in Excel to Image file?

The following VBA code is a User Defined Function (UDF) that can save a group of continuous cells as a JPG file.

This UDF has one argument, which is defined at line 1 as imageRng. When using this function, it will expect the user to select a range of cells.

Lines 2 – 4 are declaring the variable sImageFilePath, which will contain the location and the name of the to be saved JPG file.

Line 5 – 6 are declaring and opening a new clean Excel workbook under the variable wbTemp, which will function as a mnemonic in the creation of the JPG file.

Line 7 – 13 will copy and paste imageRng as a picture in wbTemp and save it as a JPG file at location sImageFilePath.

Line 14 – 16 will produce a dialog box about the whereabouts of the JPG file and cleanup wbTemp to make the function ready for the next image to be saved as JPG.


Sub ExcelToJPGImage(imageRng As Range)
    'Code from officetricks.com
    Dim sImageFilePath As String
    sImageFilePath = ThisWorkbook.Path & Application.PathSeparator & "ExcelRangeToImage_"
    sImageFilePath = sImageFilePath & VBA.Format(VBA.Now, "DD_MMM_YY_HH_MM_SS_AM/PM") & ".jpg"
    
    'Create Temporary workbook to hold image
    Dim wbTemp As Workbook
    Set wbTemp = Workbooks.Add(1)
    
    'Copy image & Save to new file
    imageRng.CopyPicture xlScreen, xlPicture
    wbTemp.Activate
    With wbTemp.Worksheets("Sheet1").ChartObjects.Add(imageRng.Left, imageRng.Top, imageRng.Width, imageRng.Height)
        .Activate
        .Chart.Paste
        .Chart.Export Filename:=sImageFilePath, FilterName:="jpg"
    End With

    'Close Temp workbook
    wbTemp.Close False
    Set wbTemp = Nothing
    MsgBox "Image File Saved To: " & sImageFilePath
End Sub

If you would like to know more about how to do this refer to the below link as well.

External link: Learn to save Excel file as image