Can Someone Tell Me If This Should Work Please

rockyw

Well-known Member
Joined
Dec 26, 2010
Messages
1,196
Office Version
  1. 2010
Platform
  1. Windows
I found this insert macro but I cannot get it to work.

Code:
Sub InsertPictures()

Dim row As Long

Dim picPath As String

Dim Picture As Object



row = 1



On Error Resume Next



While Cells(row, 1) <> ""

  Cells(row, 3).Select

  

  ' just guess what type of picture it is: .jpg or .gif

  picPath = Cells(row, 2) & Cells(row, 1) & ".gif"

  ActiveSheet.Pictures.Insert(picPath).Select

  picPath = Cells(row, 2) & Cells(row, 1) & ".jpg"

  ActiveSheet.Pictures.Insert(picPath).Select

  

  Set Picture = Selection

  'set cell height to picture size

  Picture.Top = Picture.TopLeftCell.Top

  Picture.Left = Picture.TopLeftCell.Left

  Picture.TopLeftCell.EntireRow.RowHeight = Picture.Height

   row = row + 1

Wend

End Sub
The instructions said...
Column A = imagename (AL-100Y)
Column B = imagepath (c:vonnieimages)
Column C = place to insert image
Image extension can be jpg or gif

I put in column A 01
In column B C:Pictures
I can not get this to work. Can someone tell me what might be wrong? Do I need more in A and B. Thanks
 
Rocky;
The below is a complete re-write; so can start with a new workbook and paste all into a module.
This version requires adding a reference to Microsoft Scripting Runtime
Alt F11 / Tools/References then make sure 'Microsoft Scripting Runtime' is checked.

All of the Constants are used for defaults, but you're prompted to allow to change them to affect how the program operates.


There are 4 basic parts
Get the parameters [prompts]
Prompt for the folder to look for pictures
Look through that folder an load pictures into a HashTable/Index [That inherently sorts.]
Then it loops through that index and places pictures (following the parameters from earlier)





Code:
Option Explicit

'Set recommendations for parameters requested via InputBox
Const recstartrow = 5
Const recstartcol = 3
Const reccolshift = 3
Const recrowshift = 3
Const recDfltPicHeight = 75
Const recDfltPicWidth = 75
Const recDfltColWidth = 15
Const recWrapAtCol = 12

Dim Shp As Shape    'Shape object to which pictures are loaded
Dim RootPath As String  'Holds the path to files
Dim swUseKillShapes As Boolean  'Controls is Activesheet is cleared
Dim swCancel As Integer 'Switch to test if user wants to cancel at any time in the dialogs

Dim startrow, rowshift, startcol, colshift, _
DfltPicHeight, DfltPicWidth, DfltColWidth, WrapAtCol, _
nextrow, nextcol As Long
Dim i As Integer


'Requires reference to Microsoft Scripting Runtime
' IDE menu Tools/References
Dim HashTable As New Scripting.Dictionary
Dim keez    'Array for HashTable Keys
Dim picfile As String

Sub LoadPicsLeftToRight()
    On Error GoTo LoadPics_Error
    Application.ScreenUpdating = False


GetParms:

    Do
        startrow = Application.InputBox("Start Images at row: ", , Default:=recstartrow, Type:=1)
        If startrow = False Then GoSub DesireToCancel
    Loop While startrow = False

    Do
        rowshift = Application.InputBox("Place Images with this many rows of separation: ", , Default:=recrowshift, Type:=1)
        If rowshift = False Then GoSub DesireToCancel
    Loop While rowshift = False

    Do
        startcol = Application.InputBox("Start Images at column: ", , Default:=recstartcol, Type:=1)
        If startcol = False Then GoSub DesireToCancel
    Loop While startcol = False

    Do
        colshift = Application.InputBox("Place Images with this many columns of separation: ", , Default:=reccolshift, Type:=1)
        If colshift = False Then GoSub DesireToCancel
    Loop While colshift = False

    Do
        DfltPicHeight = Application.InputBox("The Images should have default height of: ", , Default:=recDfltPicHeight, Type:=1)
        If DfltPicHeight = False Then GoSub DesireToCancel
    Loop While DfltPicHeight = False

    Do
        DfltPicWidth = Application.InputBox("The Images should have default width of: ", , Default:=recDfltPicWidth, Type:=1)
        If DfltPicWidth = False Then GoSub DesireToCancel
    Loop While DfltPicWidth = False
    Do
        DfltColWidth = Application.InputBox("Default Column widths to: ", , Default:=recDfltColWidth, Type:=1)
        If DfltColWidth = False Then GoSub DesireToCancel
    Loop While DfltColWidth = False

    Do
        WrapAtCol = Application.InputBox("Jump to the next row if the image would be placed after column: ", , Default:=recWrapAtCol, Type:=1)
        If WrapAtCol = False Then GoSub DesireToCancel
    Loop While WrapAtCol = False

Process:
    Do
        RootPath = BrowseForFolder

        If RootPath = "False" Then GoSub DesireToCancel
    Loop While RootPath = "False"
    
    If RootPath <> "False" Then RootPath = RootPath & "\"
    LoadHashTable

    If HashTable.Count < 1 Then Exit Sub

    nextrow = startrow
    nextcol = startcol

    KillShapesII    'Deletes all shapes/pictures and text of the active sheet

    With ActiveSheet
        keez = HashTable.Keys              ' Get the keys.
        For i = 0 To HashTable.Count - 1    ' Iterate the array.
            If HashTable.Exists(keez(i)) Then
                picfile = HashTable.Item(keez(i))
                .Cells(nextrow, nextcol).Select

                'Method Insert Shape
                Set Shp = .Shapes.AddPicture(picfile, msoFalse, msoCTrue, .Cells(nextrow, nextcol).Left, .Cells(nextrow, nextcol).Top, DfltPicWidth, DfltPicHeight)
                .Cells(nextrow, nextcol).RowHeight = Shp.Height
                .Cells(nextrow, nextcol).ColumnWidth = DfltColWidth
                .Cells(nextrow + 1, nextcol) = keez(i)

            End If

            'Determine the column for the next pic
            nextcol = nextcol + 2
            If nextcol > WrapAtCol Then
                nextcol = startcol
                nextrow = nextrow + rowshift
            Else
                nextcol = nextcol
                nextrow = nextrow
            End If
            DoEvents    'Allows computer to process other things in intense loops
        Next i
    End With

    On Error GoTo 0
    Exit Sub

DesireToCancel:
'Manages messaging to user & prog. flow when cancel condition may be present
    swCancel = MsgBox("Do you want to cancel?", vbYesNo)
    Select Case swCancel
        Case Is = vbYes
            MsgBox "Exiting"
            Exit Sub
        Case Is = vbNo
            Return
    End Select

LoadPics_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure LoadPics " & vbLf & picfile
    Err = 0
End Sub
Private Function LoadHashTable()
    'Load Dictionary/Index
    'A Dictionary/Index is an ordered list
    'Omits the need to bubble sort an array
    
    'clear hashtable
    HashTable.RemoveAll
    
    For i = 1 To 2
        'Initialize picfile/Dir function
        If i = 1 Then picfile = Dir(RootPath & "*.jpg")
        If i = 2 Then picfile = Dir(RootPath & "*.gif")

        Do While picfile <> ""
            HashTable.Add picfile, RootPath & picfile
            picfile = Dir()
            DoEvents    'Allows computer to process other things in intense loops
        Loop
    Next
End Function

Sub KillShapesII()
    Application.ScreenUpdating = False
    With ActiveSheet
        If .Shapes.Count > 0 Then
            .Shapes.SelectAll
            Selection.Delete
        End If
        .Cells.Clear
    End With
End Sub

Function BrowseForFolder(Optional OpenAt As Variant) As Variant
    'Citation: By Ken Puls http://www.vbaexpress.com/kb/getarticle.php?kb_id=284
    
     'Function purpose:  To Browser for a user selected folder.
     'If the "OpenAt" path is provided, open the browser at that directory
     'NOTE:  If invalid, it will open at the Desktop level
     
    Dim ShellApp As Object
     
     'Create a file browser window at the default folder
    Set ShellApp = CreateObject("Shell.Application"). _
    BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
     
     'Set the folder to that selected.  (On error in case cancelled)
    On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
    On Error GoTo 0
     
     'Destroy the Shell Application
    Set ShellApp = Nothing
     
     'Check for invalid or non-entries and send to the Invalid error
     'handler if found
     'Valid selections can begin L: (where L is a letter) or
     '\\ (as in \\servername\sharename.  All others are invalid
    Select Case Mid(BrowseForFolder, 2, 1)
    Case Is = ":"
        If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
    Case Is = "\"
        If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
    Case Else
        GoTo Invalid
    End Select
     
    Exit Function
     
Invalid:
     'If it was determined that the selection was invalid, set to False
    BrowseForFolder = False
     
End Function
 
Upvote 0

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
You are amazing! seriously. I have to head out of here but I ran this 2 times and it worked perfectly. I love the way you built in the choice for selections. I hope a lot of people can benefit from this that need a great code to load images. I’m sorry I asked for something different but after thinking about it inserting rows first seemed better so I could insert images alphabetical or numeral sequence. Thanks again and have a great week.
 
Upvote 0
tweedle This works great, thank you so much. I'm going to start putting the picture album together this week. Is there a simple way to just bring in the name and not the .jpg? I tried a couple things but without success. If it's hard to do forget it, Thanks
 
Upvote 0
Glad it's flying well for you.

replace
Code:
.Cells(nextrow + 1, nextcol) = keez(i)
with
Code:
.Cells(nextrow + 1, nextcol) = Replace(Replace(keez(i), ".jpg", ""), ".gif", "")
should do the trick (as long as they don't have .jpg or .gif in their proper name ;) )


fyi: I knew that was coming...
 
Upvote 0
Spot on as normal. This will save me changing 400 names. Thanks again
 
Upvote 0
This is confusing so I hope someone can explain this. I asked that the code be changed so the jpg will not be seen in the name. SOME images work this way, others don’t. When I look at the name all I see is Doe, John that’s it. I even used batch rename and it still brings in the jpg. Is there something I’m missing? Is there a way to rename an image I’m not aware of? Thanks
 
Upvote 0
Can you provide some examples of original file names that do work and some that do not work?
 
Upvote 0
I feel really stupid but here's the problem. When I saved some of these images the default extension was set to JPG, not jpg. All I have to do is batch rename to small caps on the extension, or change the code to CAPS. That was a brain twister but all is well. Sorry for crying wolf but thanks for coming to the rescue. Have a great superbowl weekend. THANKS!!!!
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,175
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