View Full Version : [SOLVED:] Using Dir() to return name of all images
noslenwerd
12-24-2019, 11:44 AM
Hello,
I am trying to write a simple macro that will check for any files with the term 'logo' in it, but this code doesn't seem to be working. There is a logo.jpg file in the current directory. Any ideas?
Sub Logocheck()
Dim ImgName As String
Dim ImgPath As String
ImgPath = ThisDocument.Path
ImgName = Dir(ImgPath & "logo.*")
MsgBox ImgName
End Sub
The actual application of this is will be to insert any image file with the name 'logo' in it, into the header of the word document.
This is only posted on this forum.
gmayor
12-24-2019, 10:36 PM
Change the line
ImgPath = ThisDocument.Path
to
ImgPath = ThisDocument.Path & "\"
better still
Sub Logocheck()
Dim ImgName As String
Dim ImgPath As String
ImgPath = ThisDocument.Path
ImgName = Dir$(ImgPath & "\*logo*")
While ImgName <> ""
MsgBox ImgName
ImgName = Dir$()
Wend
End Sub
noslenwerd
12-26-2019, 08:02 AM
Change the line
ImgPath = ThisDocument.Path
to
ImgPath = ThisDocument.Path & "\"
better still
Sub Logocheck()
Dim ImgName As String
Dim ImgPath As String
ImgPath = ThisDocument.Path
ImgName = Dir$(ImgPath & "\*logo*")
While ImgName <> ""
MsgBox ImgName
ImgName = Dir$()
Wend
End Sub
Perfect! Thank you for this.
Works beautifully.
noslenwerd
12-26-2019, 08:13 AM
Not sure if this would require a new thread, but i am trying to parlay this into inserting the found image into the header of my document. I am getting Run-time error '5152' This is not a valid filename on the bolded line below:
Sub Logocheck()Dim oLogo As InlineShape
Dim ImgName As String
Dim ImgPath As String
Dim oSec As Section
Dim oHeader As HeaderFooter
ImgPath = ThisDocument.Path
ImgName = Dir$(ImgPath & "\*logo*")
If ImgName = vbNullString Then
MsgBox "Please note logo image was not found. You will need to manually insert the company logo into your final review."
End If
For Each oSec In ActiveDocument.Sections
Set oHeader = oSec.Headers(wdHeaderFooterPrimary)
With oHeader.Range
.ParagraphFormat.Alignment = wdAlignParagraphRight
Set oLogo = .InlineShapes.AddPicture(ImgName)
End With
With oLogo
.LockAspectRatio = True
.Height = 50
End With
Next oSec
End Sub
gmayor
12-26-2019, 09:36 PM
The issue is similar. ImgPath returns the name without the path. Change the line:
Set oLogo = .InlineShapes.AddPicture(ImgPath)
to
Set oLogo = .InlineShapes.AddPicture(ImgPath & "\" & ImgName)
also add
Exit Sub
after the message box.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.