View Full Version : Inserting bulk pictures into bookmark locations
whitelillie
02-08-2017, 07:11 PM
I have a word document that has a number of bookmarks (ie Scorecard, YTDResults etc).
I also have a folder that has images with the same names as the bookmarks.
I need a code that will:
go to the first bookmark
make note of the bookmark name
insert a picture named the same as the bookmark from a set file location
move to the next bookmark and repeat
gmayor
02-08-2017, 09:50 PM
The following will insert any image in the named folder at a bookmark that shares the filename (without the extension). Images in the folder that don't match bookmark names are ignored.
Use a folder that doesn't contain files that are not images as the process checks all filenames!
Option Explicit
Sub InsertImages()
Dim strFile As String
Dim strBookmark As String
Const strPath As String = "E:\Path\Images\" 'the folder with the images
strFile = Dir$(strPath & "*.*")
While strFile <> ""
strBookmark = Left(strFile, InStrRev(strFile, Chr(46)) - 1)
strBookmark = Replace(strBookmark, Chr(32), "")
ImageToBM strBookmark, strPath & strFile
strFile = Dir$()
Wend
End Sub
Private Sub ImageToBM(strBMName As String, strImagePath As String)
'Graham Mayor - http://www.gmayor.com
Dim oRng As Range
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strImagePath) Then
With ActiveDocument
On Error GoTo lbl_Exit
Set oRng = .Bookmarks(strBMName).Range
oRng.Text = ""
oRng.InlineShapes.AddPicture _
FileName:=strImagePath, LinkToFile:=False, _
SaveWithDocument:=True
oRng.End = oRng.End + 1
oRng.Bookmarks.Add strBMName
End With
End If
lbl_Exit:
Set fso = Nothing
Set oRng = Nothing
Exit Sub
End Sub
whitelillie
02-09-2017, 02:31 PM
Thank you so much Graham. The code does exactly what I want :)
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.