Forum Discussion

a20222125's avatar
a20222125
Copper Contributor
Jun 16, 2024

VBA that will insert and save images in folder

Looking for a VBA code that will insert an image from a local path and then save all the inserted images in a folder with the file name in one of the columns

1 Reply

  • Column A: File paths of images.
    Column B: File names (for saving images)

    Sub InsertAndSaveImages()
    Dim ws As Worksheet
    Dim imgPath As String
    Dim savePath As String
    Dim imgName As String
    Dim i As Integer
    Dim pic As Picture

    ' Define worksheet and save path
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
    savePath = "C:\Your\Folder\Path\" ' Change to your folder path

    ' Loop through rows to insert and save images
    i = 1
    Do While ws.Cells(i, 1).Value <> ""
    imgPath = ws.Cells(i, 1).Value
    imgName = ws.Cells(i, 2).Value

    ' Insert image into the worksheet
    Set pic = ws.Pictures.Insert(imgPath)
    With pic
    .Top = ws.Cells(i, 3).Top ' Adjust the column if needed
    .Left = ws.Cells(i, 3).Left ' Adjust the column if needed
    .Width = 100 ' Adjust width if needed
    .Height = 100 ' Adjust height if needed
    End With

    ' Save image to the specified folder
    Call SaveImageFromSheet(ws, pic, savePath & imgName & ".jpg") ' Adjust file format if needed

    i = i + 1
    Loop

    MsgBox "Images inserted and saved successfully!"
    End Sub

    Sub SaveImageFromSheet(ws As Worksheet, pic As Picture, saveAsPath As String)
    Dim imgShape As Shape
    Dim tempChart As ChartObject
    Dim imgPath As String

    ' Add a chart object to export image
    Set tempChart = ws.ChartObjects.Add(0, 0, pic.Width, pic.Height)
    tempChart.Chart.Pictures.Paste
    tempChart.Chart.Export Filename:=saveAsPath, FilterName:="JPG"

    ' Clean up
    tempChart.Delete
    End Sub

Resources