Summer
Summer

Reputation: 21

Add an attachment knowing the file path but not the file name

Using VBA, I've been trying to attach all JPG files in a directory to an email without knowing the exact filenames. I tried these lines of code:

.Attachments.Add "C:\Desktop\Attachments\" & "*.jpg"
.Attachments.Add "C:\Desktop\Attachments\*.jpg"
.Attachments.Add "C:\Desktop\Attachments" & "\*.jpg"

None of these worked. How do I do this?

Upvotes: 1

Views: 2499

Answers (2)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66215

Try something like the following

 Set fso = CreateObject("Scripting.FileSystemObject")
 For Each fsoFile In fso.GetFolder("C:\Desktop\Attachments").Files
   If fso.GetExtensionName(fsoFile) = "jpg" Then
     .Attachments.Add fsoFile.Path
   End If
 Next

Upvotes: 3

Justin
Justin

Reputation: 611

You need to supply an actual file path per the documentation.

https://msdn.microsoft.com/en-us/library/office/ff869553.aspx

I think you could get each file path like this:

Dim fileName as String
fileName = Dir("C:\Desktop\Attachments\*.jpg")

Do While Len(fileName) > 0
    .Attachments.Add "C:\Desktop\Attachments\" & fileName
    fileName = Dir
Loop

Upvotes: 1

Related Questions