VBA macro to Insert images into a grid pattern in excel worksheet. [2 columns, unlimited rows, empty cell in-between]

Phenotype

New Member
Joined
Dec 19, 2016
Messages
2
Hi,


I've tried multiple macros on the internet that get very close to what I need but just need a few tweaks I'm unable to figure out.

I need a macro that can insert photos from a folder into a grid pattern into an excel worksheet.

The grid would be 2 columns across by an unlimited number of rows. Ideally, in the cell directly below each photo there would be an empty cell for a short caption.

Furthermore, the photos need to be in order, that is: Image 1 in A1, Image 2 in B1, Image 3 in A3, Image 4 in B3 (until the source folder is empty). I'd like to fit in 6 decently sized images per page.

The macro which is the closest to what I need can be found at the bottom of this thread (posted by Perpa): http://www.mrexcel.com/forum/excel-questions/897485-create-macro-insert-photos-into-excel-grid.html

The macro in the above thread manages to insert images in a 3 column, unlimited row format with an empty cell to enter a comment but not in order I need!

Our IT specialist is away on holidays so I spent a solid day failing miserably at solving this so any help will be greatly appreciated!


Cheers,
Phenotype.
 

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
The macro which is the closest to what I need can be found at the bottom of this thread (posted by Perpa): http://www.mrexcel.com/forum/excel-questions/897485-create-macro-insert-photos-into-excel-grid.html
QUOTE]

Phenotype,
This proceedure uses both Sheet1 and Sheet2. Sheet1 is the picture display sheet, Sheet 2 is used to sort the filename list. You will have to adjust your margins TOP and BOTTOM to achieve the layout you want. I held the picture HEIGHT to maintain the aspect ratio of the original image in both Functions. You can hold both HEIGHT and WIDTH but there maybe some distortion.

There are two code snippets, one to sort the filenames, the other to place the pictures using the 2 Functions.

Before running the code below, this formula must be copied into Sheet2 cell I1:

' =TRIM(RIGHT(SUBSTITUTE(A1,"",REPT(" ",50)),50))'

The formula separates the filename from the complete file path which is in Column A. The filename is used below each picture on Sheet1.
Happy Holidays!
Perpa

Code:
Sub AddOlEObject_2x3()
    Dim mainWorkBook As Workbook
    Dim counter, rw, LR As Long
    Application.ScreenUpdating = False
    Set mainWorkBook = ActiveWorkbook
    Sheets("Sheet1").Activate    'Change the sheet name from "Sheet1" to the sheet name where you want your pictures to go
    
    'Clear Sheet1
    ActiveSheet.UsedRange.ClearContents
    For Each sh In Sheets("Sheet1").Shapes
       sh.Delete
    Next sh
    'Change the folderpath to wherever your pictures are coming from
    Folderpath = InputBox("Enter the complete folder path to you files" & Chr(13) & " in this format: 'C:\yourPath\folder1'")
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    rw = 1
    For Each fls In listfiles
        Sheets("Sheet2").Range("A" & rw).Value = fls
        rw = rw + 1
    Next fls
    Call SortMyFiles
    
    LR = Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
    For rw = 1 To LR Step 2
        Sheets("Sheet1").Range("A" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw).Value
        Sheets("Sheet1").Range("A" & rw + 1).RowHeight = 16
        Sheets("Sheet1").Range("A" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Sheets("Sheet1").Range("A" & rw).RowHeight = 200       'Adjust ROWS to fit your pictures
        Call insert1(Sheets("Sheet2").Range("A" & rw).Value, rw)
    Next rw
    
    For rw = 1 To LR Step 2
        Sheets("Sheet1").Range("B" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw + 1).Value
        Sheets("Sheet1").Range("B" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Call insert2(Sheets("Sheet2").Range("A" & rw + 1).Value, rw)
    Next rw
 Sheets("Sheet1").Activate
Application.ScreenUpdating = True
End Sub

Sub SortMyFiles()
Dim LR, rw As Long
    LR = Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Select
    Range("A1:A" & LR).Select
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet2").Sort
        .SetRange Range("A1:A" & LR)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    With Sheets("Sheet2")
        .Activate
        LR = .Range("A" & Rows.Count).End(xlUp).Row
        For rw = 2 To LR
        'Copies formula
            .Range("I1").Copy     'This is the formula to find the filename
            .Range("I" & rw).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
                SkipBlanks:=False, Transpose:=False
        Next rw
    End With
         
    Range("A" & LR + 1).Activate
    Sheets("Sheet1").Activate
End Sub

Function insert1(PicPath, counter1)
'Formats Column A Pictures
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue    'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT
            .Height = 198    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("A" & counter1).Left
        .Top = ActiveSheet.Range("A" & counter1).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function

Function insert2(PicPath, counter2)
'Formats Column B Pictures
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue      'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT with the single quote
            .Height = 198    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("B" & counter2).Left
        .Top = ActiveSheet.Range("B" & counter2).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function
 
Upvote 0
I am trying to adapt this code to put 3 pictures on a row instead of 2. I copied the 2 relevant code sections and created a 3rd action for each. The new code is adding a 3rd picture to each row, but duplicating the same picture on the next row. I have 12 pictures in my folder, but I end up with 17 images, 5 of which are duplicates. I also get an "Error 1004:Unable to get the insert property of the Pictures class" on the third "ActiveSheet.Pictures.insert(PicPath). Can anyone advise on what I did wrong in setting up the third step for each?

Thank you!!

Code:
    For rw = 1 To LR Step 2
        Sheets("Sheet1").Range("B" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw + 1).Value
        Sheets("Sheet1").Range("B" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Call insert2(Sheets("Sheet2").Range("A" & rw + 1).Value, rw)
    Next rw
 
     For rw = 1 To LR Step 2
        Sheets("Sheet1").Range("C" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw + 2).Value
        Sheets("Sheet1").Range("C" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Call insert3(Sheets("Sheet2").Range("A" & rw + 2).Value, rw)
    Next rw



Code:
Function insert2(PicPath, counter2)
'Formats Column B Pictures
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue      'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT with the single quote
            .Height = 198    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("B" & counter2).Left
        .Top = ActiveSheet.Range("B" & counter2).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function


Function insert3(PicPath, counter3)
'Formats Column C Pictures
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue      'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT with the single quote
            .Height = 198    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("C" & counter3).Left
        .Top = ActiveSheet.Range("C" & counter3).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function
 
Last edited:
Upvote 0
RChapman9,
It has been a while on this one!
Try changing the 'Step 2' to 'Step 3' on all three of the 'For/Next' statements and let me know if that solved your issue.
I will be unavailable until this evening, but will check back then.
Perpa
 
Upvote 0
Perpa,

Thank you so much!! I will try it right away and let you know. And thank you for sharing this fabulous code!!

Robyn
 
Upvote 0
Perpa or others--

This code works great for my first folder of images. When I move down the page and try to run it again on another image folder, it puts the new pictures on top of the old ones, and overwrites the filenames under each picture. I need to run this for up to 20 folders going down the same sheet. Is that possible with this code?

Thanks so much!!
Robyn
 
Upvote 0
Robyn,
I am glad the code worked for you with that simple 'Step' change...You are most welcome.

However, I am a bit perplexed by your subsequent post:
"This code works great for my first folder of images. When I move down the page and try to run it again on another image folder,
it puts the new pictures on top of the old ones, and overwrites the filenames under each picture. I need to run this for up to
20 folders going down the same sheet. Is that possible with this code?"

The code listed in post #2 of this thread has elements to 'Clear Sheet1', so I am not clear on why you would be putting
"...the new pictures on top of the old ones, and overwrites the filenames under each picture."

It would be helpful if you could post the complete code you are using, then maybe we can get a clearer picture of what you are doing.

In the meantime just a couple of 'non-code' methods for consideration you might try:
You could copy all the files from all 20 folders to one Master Folder, then run the macro on the Master Folder.
OR...
Run the macro on each folder (Path) then copy each result to a Master Folder with the pathname (or folder name) for each folder shown before the first picture in each folder.

Perpa
 
Upvote 0
Perpa,

Thank you so much for the change to explain further!

My client does construction retrofitting. A typical job will have 10-20 buildings (e.g. schools, municipal buildings), and the proposal needs to include 10-12 pictures of each building. A site visit may include 100+ pictures of each location. The project manager selects the best 10-12 images from each location and saves them in a folder for that location. Sample folder structure is below. The client wants all pictures for the proposal on a single Excel tab. So there could be 20 groupings of 12 photos each on a single tab. I’m trying to adapt the code to insert the images for Smith ES, then insert Jones ES a few rows down, then insert Johnson MS, then Anderson HS, etc. Additional information is then added between each picture grouping.

Currently, I can run the first one (e.g., Smith ES) successfully. I move down a few rows and try to run Jones ES. The macro starts at the top, writes over the filename captions, and pastes the Jones pictures on top of the Smith pictures. (It doesn’t delete the Smith pictures, just adds the Jones pictures.) Code is below.

How can I keep it from going back up to the top of the sheet when I run it for the second and subsequent buildings?

Folder structure:

Atlanta County Schools
-Smith ES
--Cafeteria 1.jpg
--Cafeteria 2.jpg
--Exterior.jpg
--Classroom 1.jpg
--Classroom 2.jpg
--Office 1.jpg
--Office 2.jpg
--Hallway 1.jpg
-Jones ES
--Cafeteria 1.jpg
--Cafeteria 2.jpg
--Exterior.jpg
--Classroom 1.jpg
--Classroom 2.jpg
--Office 1.jpg
--Office 2.jpg
--Hallway 1.jpg
-Johnson MS
--Exterior.jpg
--Office.jpg
--Classroom 1.jpg
--Classroom 2.jpg
--Hallway 1.jpg
--Gym 1.jpg
--Gym 2.jpg
--Cafeteria 1.jpg
-Anderson HS
--Exterior.jpg
--Office.jpg
--Classroom 1.jpg
--Classroom 2.jpg
--Hallway 1.jpg
--Gym 1.jpg
--Gym 2.jpg
--Cafeteria 1.jpg
--Auditorium.jpg
--Bandroom.jpg
--Studio.jpg
--Computer Room.jpg





Code:
Sub AddOlEObject_2x3Orig()
    Dim mainWorkBook As Workbook
    Dim counter, rw, LR, ac As Long
    'Dim oPic As Shape
    Application.ScreenUpdating = False
    Set mainWorkBook = ActiveWorkbook
    Sheets("Sheet1").Activate    'Change the sheet name from "Sheet1" to the sheet name where you want your pictures to go
    'ActiveCell.Select
    
    'Clear Sheet1
    'ActiveSheet.UsedRange.ClearContents
    'For Each sh In Sheets("Sheet1").Shapes
    '   sh.Delete
    'Next sh
    'Change the folderpath to wherever your pictures are coming from
    Folderpath = InputBox("Enter the complete folder path to your files" & Chr(13) & " in this format: 'C:\yourPath\folder1'")
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    rw = 1
    For Each fls In listfiles
        Sheets("Sheet2").Range("A" & rw).Value = fls
        rw = rw + 1
    Next fls
    Call SortMyFiles
    
    LR = Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
    ac = ActiveCell.Row
    For rw = 1 To LR Step 3
        Sheets("Sheet1").Range("B" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw).Value
        Sheets("Sheet1").Range("B" & rw + 1).RowHeight = 16
        'Sheets("Sheet1").Range("B" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Sheets("Sheet1").Range("B" & rw).RowHeight = 220       'Adjust ROWS to fit your pictures
        Call insert1(Sheets("Sheet2").Range("A" & rw).Value, rw)
    Next rw
    
    For rw = 1 To LR Step 3
        Sheets("Sheet1").Range("E" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw + 1).Value
        'Sheets("Sheet1").Range("E" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
        Call insert2(Sheets("Sheet2").Range("A" & rw + 1).Value, rw)
    Next rw
 
    For rw = 1 To LR Step 3
       Sheets("Sheet1").Range("M" & rw + 1).Value = Sheets("Sheet2").Range("I" & rw + 2).Value
       'Sheets("Sheet1").Range("M" & rw).ColumnWidth = 50     'Adjust COLUMNS to fit your pictures
       Call insert3(Sheets("Sheet2").Range("A" & rw + 2).Value, rw)
    Next rw
 
 Sheets("Sheet1").Activate
Application.ScreenUpdating = True
End Sub


Sub SortMyFiles()
Dim LR, rw As Long
    LR = Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Select
    Range("A1:A" & LR).Select
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet2").Sort
        .SetRange Range("A1:A" & LR)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    With Sheets("Sheet2")
        .Activate
        LR = .Range("A" & Rows.Count).End(xlUp).Row
        For rw = 2 To LR
        'Copies formula
            .Range("I1").Copy     'This is the formula to find the filename
            .Range("I" & rw).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
                SkipBlanks:=False, Transpose:=False
        Next rw
    End With
         
    Range("A" & LR + 1).Activate
    Sheets("Sheet1").Activate
End Sub


Function insert1(PicPath, counter1)
'Formats Column A Pictures
    With ActiveSheet.Pictures.Insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue    'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT
            .Height = 215    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("B" & counter1).Left
        .Top = ActiveSheet.Range("B" & counter1).Top
        .Placement = 1
        .PrintObject = True
    End With
    ActiveCell.Offset(1, 0).Select
    
End Function


Function insert2(PicPath, counter2)
'Formats Column B Pictures
    With ActiveSheet.Pictures.Insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue      'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT with the single quote
            .Height = 215    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("E" & counter2).Left
        .Top = ActiveSheet.Range("E" & counter2).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function




Function insert3(PicPath, counter3)
'Formats Column C Pictures
    With ActiveSheet.Pictures.Insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue      'If you uncomment both Width and Height lines below change to 'msoFalse'
            '.Width = 50      'Adjust to change the WIDTH of your pictures - COMMENTED OUT with the single quote
            .Height = 215    'Adjust to change the HEIGHT of your pictures
        End With
        .Left = ActiveSheet.Range("M" & counter3).Left
        .Top = ActiveSheet.Range("M" & counter3).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,820
Messages
6,181,161
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top