Microsoft Office Forums

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 02-10-2020, 08:27 PM
henhelm henhelm is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 10 Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2016
Novice
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet
 
Join Date: Jun 2019
Posts: 7
henhelm is on a distinguished road
Default Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet

I was looking for help with a Word macro that could do the following:

(1) Insert multiple photos into a word document without having to navigate through a directory to find the photo folder. (2) Retrieve and insert the captions for those photos from a column of data in an excel sheet. (3) Format the caption font to a certain font style.

I would sincerely appreciate your help.

Macropod has graciously provided this code, but the user must navigate to the file folder containing the photos and the captions are created based on the image names (I apologize if I am not pasting this code correctly):

Code:
Sub AddPics()
Application.ScreenUpdating = False
Dim i As Long, j As Long, c As Long, r As Long, NumCols As Long, iShp As InlineShape
Dim oTbl As Table, TblWdth As Single, StrTxt As String, RwHght As Single, ColWdth As Single
On Error GoTo ErrExit
NumCols = CLng(InputBox("How Many Columns per Row?"))
RwHght = CentimetersToPoints(CSng(InputBox("What max height for the pictures, in centimeters (e.g. 5)?")))
On Error GoTo 0
'Select and insert the Pics
With Application.FileDialog(msoFileDialogFilePicker)
  .Title = "Select image files and click OK"
  .Filters.Add "Images", "*.gif; *.jpg; *.jpeg; *.bmp; *.tif; *.png"
  .FilterIndex = 2
  If .Show = -1 Then
    'Create a paragraph Style with 0 space before/after & centre-aligned
    On Error Resume Next
    With ActiveDocument
      .Styles.Add Name:="TblPic", Type:=wdStyleTypeParagraph
      On Error GoTo 0
      With .Styles("TblPic").ParagraphFormat
        .Alignment = wdAlignParagraphCenter
        .KeepWithNext = True
        .SpaceAfter = 0
        .SpaceBefore = 0
      End With
    End With
    'Add a 2-row by NumCols-column table to take the images
    Set oTbl = Selection.Tables.Add(Range:=Selection.Range, NumRows:=2, NumColumns:=NumCols)
    With ActiveDocument.PageSetup
      TblWdth = .PageWidth - .LeftMargin - .RightMargin - .Gutter
      ColWdth = TblWdth / NumCols
    End With
    With oTbl
      .AutoFitBehavior (wdAutoFitFixed)
      .Columns.Width = ColWdth
    End With
    CaptionLabels.Add Name:="Picture"
    For i = 1 To .SelectedItems.Count Step NumCols
      r = ((i - 1) / NumCols + 1) * 2 - 1
      'Format the rows
      Call FormatRows(oTbl, r, RwHght)
      For c = 1 To NumCols
        j = j + 1
        'Insert the Picture
        Set iShp = ActiveDocument.InlineShapes.AddPicture( _
          FileName:=.SelectedItems(j), LinkToFile:=False, _
          SaveWithDocument:=True, Range:=oTbl.Cell(r, c).Range)
        With iShp
          .LockAspectRatio = True
          If (.Width < ColWdth) And (.Height < RwHght) Then
            .Width = ColWdth
            If .Height > RwHght Then .Height = RwHght
          End If
        End With
        'Get the Image name for the Caption
        StrTxt = Split(.SelectedItems(j), "")(UBound(Split(.SelectedItems(j), "")))
        StrTxt = ": " & Split(StrTxt, ".")(0)
        'Insert the Caption on the row below the picture
        With oTbl.Cell(r + 1, c).Range
          .InsertBefore vbCr
          .Characters.First.InsertCaption _
          Label:="Picture", Title:=StrTxt, _
          Position:=wdCaptionPositionBelow, ExcludeLabel:=False
          .Characters.First = vbNullString
          .Characters.Last.Previous = vbNullString
        End With
        'Exit when we're done
        If j = .SelectedItems.Count Then Exit For
      Next
      'Add extra rows as needed
      If j < .SelectedItems.Count Then
        oTbl.Rows.Add
        oTbl.Rows.Add
      End If
    Next
  Else
  End If
End With
ErrExit:
Application.ScreenUpdating = True
End Sub

Sub FormatRows(oTbl As Table, x As Long, Hght As Single)
With oTbl
  With .Rows(x)
    .Height = Hght
    .HeightRule = wdRowHeightExactly
    .Range.Style = "TblPic"
    .Cells.VerticalAlignment = wdCellAlignVerticalCenter
  End With
  With .Rows(x + 1)
    .Height = CentimetersToPoints(0.5)
    .HeightRule = wdRowHeightExactly
    .Range.Style = "Caption"
  End With
End With
End Sub


Last edited by macropod; 02-10-2020 at 09:18 PM. Reason: Added code tags
Reply With Quote
  #2  
Old 02-10-2020, 09:27 PM
macropod's Avatar
macropod macropod is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 7 64bit Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 19,918
macropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud of
Default

Do the image filenames also appear in the workbook? If not, it's impossible to guarantee the captions will be assigned to the correct images. Either way, you'll need to tell us the:
• document path;
• image path;
• workbook path & name;
• worksheet name; and
• the columns the data are to be found in.
__________________
Cheers,
Paul Edstein
[MS MVP - Word]
Reply With Quote
  #3  
Old 02-10-2020, 09:45 PM
gmayor's Avatar
gmayor gmayor is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 10 Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2016
Expert
 
Join Date: Aug 2014
Posts: 3,081
gmayor is just really nicegmayor is just really nicegmayor is just really nicegmayor is just really nicegmayor is just really nice
Default

As an alternative approach, see Photo Gallery Add-in Template
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote
  #4  
Old 02-10-2020, 10:07 PM
henhelm henhelm is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 10 Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2016
Novice
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet
 
Join Date: Jun 2019
Posts: 7
henhelm is on a distinguished road
Default

Document Path: C:\Users\[username]\Box Sync\SF_Projects_Active\[project number]

Image Path: C:\Users\[username]\Box Sync\SF_Projects_Active\[project number]\[project number] Report Photos

Workbook Path: C:\Users\[username]\Box Sync\[username]\RCA

Workbook Name: Inspections

Worksheet Name: [project number] Observations

Image #s in column N

Captions in column Q

**Info in brackets is generic

Column N contains the image names that correspond to those in the folder containing the images. For example, cell N2 contains the text IMG_0001 and an image in the image folder also contains an image named IMG_0001. In column N, they do not have any extension, simply the name, e.g. IMG_0001. In the folder, they are similarly named, i.e. IMG_0001. However, when I click on the properties/details of the image, the name is IMG_0001.JPG.
Reply With Quote
  #5  
Old 02-12-2020, 08:06 PM
macropod's Avatar
macropod macropod is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 7 64bit Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 19,918
macropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud of
Default

Give the following a go:
Code:
Sub InsertReportPics()
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String, StrWkSht As String
Dim StrRpt As String, StrDocPath As String, StrPicPath As String, xlFList As String, xlCList As String
Dim iDataRow As Long, c As Long, r As Long, i As Long, j As Long, k As Long, NumCols As Long
Dim iShp As InlineShape, oTbl As Table, TblWdth As Single, RwHght As Single, ColWdth As Single
StrWkBkNm = "C:\Users\" & Environ("Username") & "\Box Sync\" & Environ("Username") & "\RCA\Inspections.xlsx"
StrDocPath = ActiveDocument.Path
StrRpt = Right(StrDocPath, Len(StrDocPath) - InStrRev(StrDocPath, "\"))
StrWkSht = StrRpt & " Observations"
StrPicPath = StrDocPath & "\" & StrRpt & " Report Photos\"
If Dir(StrWkBkNm) = "" Then
  MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
  Exit Sub
End If
On Error GoTo ErrExit
NumCols = CLng(InputBox("How Many Columns per Row?"))
RwHght = CentimetersToPoints(CSng(InputBox("What max height for the pictures, in centimeters (e.g. 5)?")))
On Error GoTo 0
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
  MsgBox "Can't start Excel.", vbExclamation
  Exit Sub
End If
On Error GoTo 0
With xlApp
  'Hide our Excel session
  .Visible = False
  ' The file is available, so open it.
  Set xlWkBk = .Workbooks.Open(FileName:=StrWkBkNm, ReadOnly:=True, AddToMru:=False)
  If xlWkBk Is Nothing Then
    MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
    .Quit
    Exit Sub
  End If
  ' Process the workbook.
  With xlWkBk
    'Ensure the worksheet exists
    If SheetExists(xlWkBk, StrWkSht) = True Then
      With .Worksheets(StrWkSht)
        ' Find the last-used row in column A.
        iDataRow = .Cells(.Rows.Count, 14).End(-4162).Row ' -4162 = xlUp
        ' Capture the F/R data.
        For i = 2 To iDataRow
          ' Skip over empty fields to preserve the underlying cell contents.
          If Trim(.Range("N" & i)) <> vbNullString Then
            xlFList = xlFList & "|" & Trim(.Range("N" & i))
            xlCList = xlCList & "|" & Trim(.Range("Q" & i))
          End If
        Next
      End With
    Else
      MsgBox "Cannot find the designated worksheet: " & StrWkSht, vbExclamation
    End If
  .Close False
  End With
  .Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
'Exit if there are no data
If xlFList = "" Then Exit Sub
With ActiveDocument
  On Error Resume Next
  .Styles.Add Name:="TblPic", Type:=wdStyleTypeParagraph
  On Error GoTo 0
  With .Styles("TblPic").ParagraphFormat
    .Alignment = wdAlignParagraphCenter
    .KeepWithNext = True
    .SpaceAfter = 0
    .SpaceBefore = 0
  End With
  With .Styles("Caption")
    With .Font
      .Name = "Times New Roman"
      .Size = 10
      .Bold = False
    End With
    .ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(2.5), Alignment:=wdAlignTabLeft
  End With
  'Add a 2-row by NumCols-column table to take the images
  Set oTbl = Selection.Tables.Add(Range:=Selection.Range, NumRows:=2, NumColumns:=NumCols)
  With .PageSetup
    TblWdth = .PageWidth - .LeftMargin - .RightMargin - .Gutter
    ColWdth = TblWdth / NumCols
  End With
  With oTbl
    .AutoFitBehavior (wdAutoFitFixed)
    .Columns.Width = ColWdth
  End With
  CaptionLabels.Add Name:="Photograph"
  'Process each file from the F/R List
  k = UBound(Split(xlFList, "|"))
  For i = 1 To k Step NumCols
    r = ((i - 1) / NumCols + 1) * 2 - 1
    'Format the rows
    Call FormatRows(oTbl, r, RwHght)
    For c = 1 To NumCols
      j = j + 1
      'Insert the Picture
      Set iShp = .InlineShapes.AddPicture( _
        FileName:=StrPicPath & Split(xlFList, "|")(j) & ".jpg", LinkToFile:=False, _
        SaveWithDocument:=True, Range:=oTbl.Cell(r, c).Range)
      With iShp
        .LockAspectRatio = True
        If (.Width < ColWdth) And (.Height < RwHght) Then
          .Width = ColWdth
          If .Height > RwHght Then .Height = RwHght
        End If
      End With
      'Insert the Caption on the row below the picture
      With oTbl.Cell(r + 1, c).Range
        .InsertBefore vbCr
        .Characters.First.InsertCaption _
          Label:="Photograph", Title:=vbTab & Split(xlCList, "|")(j), _
          Position:=wdCaptionPositionBelow, ExcludeLabel:=False
        .Characters.First = vbNullString
        .Characters.Last.Previous = vbNullString
      End With
      'Exit when we're done
      If j = k Then Exit For
    Next
    'Add extra rows as needed
    If j < k Then
      oTbl.Rows.Add
      oTbl.Rows.Add
    End If
  Next
End With
ErrExit:
Application.ScreenUpdating = True
End Sub

Function SheetExists(xlWkBk As Object, SheetName As String) As Boolean
Dim i As Long: SheetExists = False
For i = 1 To xlWkBk.Sheets.Count
  If xlWkBk.Sheets(i).Name = SheetName Then
    SheetExists = True:   Exit For
  End If
Next
End Function

Sub FormatRows(oTbl As Table, x As Long, RwHght As Single)
With oTbl
  With .Rows(x)
    .Height = RwHght
    .HeightRule = wdRowHeightExactly
    .Range.Style = "TblPic"
    .Cells.VerticalAlignment = wdCellAlignVerticalCenter
  End With
  With .Rows(x + 1)
    .Height = CentimetersToPoints(0.5)
    .HeightRule = wdRowHeightExactly
    .Range.Style = "Caption"
  End With
End With
End Sub
Note: If you'd prefer to work in inches, replace all the 'centimeters' references to 'inches' and, where that is followed by a number in parentheses, change that number to a suitable value for inches
__________________
Cheers,
Paul Edstein
[MS MVP - Word]

Last edited by macropod; Yesterday at 04:24 AM.
Reply With Quote
  #6  
Old 02-13-2020, 11:52 PM
henhelm henhelm is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 10 Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2016
Novice
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet
 
Join Date: Jun 2019
Posts: 7
henhelm is on a distinguished road
Default

Yes, thank you!

One last request . Can you help me change the captions to read "Photograph X: Caption", in Times New Roman with size 10 font, and 5 spaces between the colon and caption?
Reply With Quote
  #7  
Old 02-14-2020, 12:04 AM
henhelm henhelm is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 10 Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2016
Novice
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet
 
Join Date: Jun 2019
Posts: 7
henhelm is on a distinguished road
Default

Also, please let me know how to make a financial contribution. Thank you!
Reply With Quote
  #8  
Old 02-14-2020, 12:23 AM
macropod's Avatar
macropod macropod is offline Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Windows 7 64bit Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 19,918
macropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud ofmacropod has much to be proud of
Default

Quote:
Originally Posted by henhelm View Post
Can you help me change the captions to read "Photograph X: Caption", in Times New Roman with size 10 font, and 5 spaces between the colon and caption?
Change:
CaptionLabels.Add Name:="Picture"
to:
CaptionLabels.Add Name:="Photograph"
Change:
Label:="Picture"
to:
Label:="Photograph"
Insert:
Code:
  With .Styles("Caption")
    With .Font
      .Name = "Times New Roman"
      .Size = 10
    End With
    .ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(2.5), Alignment:=wdAlignTabLeft
  End With
before:
'Add a 2-row by NumCols-column table to take the images

Note: Word doesn't work with spaces the way I expect you want. Using a tab-stop should give a comparable result.
__________________
Cheers,
Paul Edstein
[MS MVP - Word]
Reply With Quote
Reply

Thread Tools
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Macro to access info from Excel spreadsheet and populate Word doc with text, photos, and captions henhelm Word VBA 4 06-27-2019 08:49 PM
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Inserting multiple photos at a specific size Mr M Drawing and Graphics 2 06-20-2018 08:07 PM
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Excel Macro: Multiple Search and Post in Excel Sheet andxie Excel Programming 10 05-31-2018 05:21 PM
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Inserting and formatting photos in word 2013 tha_slughy Word VBA 5 07-13-2014 04:39 PM
Macro for Inserting Multiple Photos into Word but retrieving Captions from Excel Sheet Inserting / formatting multiple photos into Word doc. Jeremiahts Drawing and Graphics 1 03-23-2011 07:33 PM


All times are GMT -7. The time now is 08:47 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2020, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2020 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft