I feel like I am 3/4 of the way to my objective. I've created VBA that will populate an automated e-mail with attachments, based on the name of a folder the user previously selected.
It goes like this:
'folderName is identified earlier
Dim files As FileDialog
Dim vrtSelectedItem As Variant
Dim list As String, wbName As String, atmpt As Long
wbName = Left(ThisWorkbook.Path, InStrRev(ThisWorkbook.Path, "/")) & _
"Registry/Joining Instructions/" & folderName & "/"
Do
Set files = Application.FileDialog(msoFileDialogFilePicker)
cnt = 0
atmpt = atmpt + 1
With files
.InitialFileName = wbName
Application.SendKeys "+{TAB}", True
Application.SendKeys "+{TAB}", True
Application.SendKeys "^a", True
Application.SendKeys "~", True
If .Show = -1 Then
'Code continues...
The reason why I don't permanently set attachment names and simply attach them to every e-mail is because these attachments are dynamic and change with certain environments. Another thing I should mention is this workbook is located on SharePoint, so FileSystemObject is out of the question. Thus, I have the FileDialog appear, locate the specific folder that was previously identified, and I have it select all files.
My goal: is to have this fully automatic (mind you, ugly to the eye as it flickers for less than a few seconds).
My issue: is that this does not work on the first try, ever. On the first atmpt
, the FileDialog opens but does not register the SendKeys. Every subsequent, uninterrupted attempt (even re-calling the subroutine) opens the FileDialog, locates the folder, selects all attachments, and closes as expected.
My question: what is making the very first instance of FileDialog different from any subsequent instance? I've perfected my SendKeys
for all subsequent openings, but if I could just code it for the first instance, anything more won't be necessary.
Any help is appreciated! Thanks, Joey
If you use the VBA-FileTools library, you can avoid using FileDialog
and SendKeys
. By using GetLocalPath, you get the traditional format for the path. And using GetFiles from the same library, you can even get all files inside a subfolder relative to your workbook like this:
Sub DemoGetLocalPath()
Dim SubFolderName As String
SubFolderName = "Subfolder"
Dim LocalFolderPath As String
LocalFolderPath = GetLocalPath(ThisWorkbook.Path)
Dim MyFiles As Collection
Set MyFiles = GetFiles(LocalFolderPath & "\" & SubFolderName)
Dim FilePath As Variant
For Each FilePath In MyFiles
Debug.Print FilePath
Next
End Sub