Link to home
Start Free TrialLog in
Avatar of laskydiver
laskydiver

asked on

Excel macro to import pictures from file

I have a list of picture names in Column A.  I want to import from a folder the images that match the names in Column A and place them in Column B beside the name.


A                                   B
Image Name            Actual Image

There are about 400 of the images. Looking for VBA code to do the import from folder.
Avatar of Joe Howard
Joe Howard
Flag of United States of America image

Give this a spin:

Option Explicit

Sub Demo()

    Dim rng As Range, cell As Range
    Dim strPicturesPath As String

    ' Set path of Pictures
    strPicturesPath = "C:\Test\"
    ' Set range containing picture names
    Set rng = Range("A1:A100")

    If Right(strPicturesPath, 1) <> "\" Then
        strPicturesPath = strPicturesPath & "\"
    End If

    On Error Resume Next
    For Each cell In rrng
        InsertPicture strPicturesPath & cell.Value, cell, True, True
    Next

End Sub

Sub InsertPicture(PictureFileName As String, TargetCell As Range, CenterH As Boolean, CenterV As Boolean)
' inserts a picture at the top left position of TargetCell
' the picture can be centered horizontally and/or vertically
    Dim p As Object, t As Double, l As Double, w As Double, h As Double
    If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub
    If Dir(PictureFileName) = "" Then Exit Sub
    ' import picture
    Set p = ActiveSheet.Pictures.Insert(PictureFileName)
    ' determine positions
    With TargetCell
        t = .Top
        l = .Left
        If CenterH Then
            w = .offset(0, 1).Left - .Left
            l = l + w / 2 - p.Width / 2
            If l < 1 Then l = 1
        End If
        If CenterV Then
            h = .offset(1, 0).Top - .Top
            t = t + h / 2 - p.Height / 2
            If t < 1 Then t = 1
        End If
    End With
    ' position picture
    With p
        .Top = t
        .Left = l
    End With
    Set p = Nothing
End Sub

Open in new window

Avatar of laskydiver
laskydiver

ASKER

MacroShadow
It worked but the images came in full size. is there a way to re-size to something manageable.
ASKER CERTIFIED SOLUTION
Avatar of Joe Howard
Joe Howard
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks