添加附件的文件路径通配符
Wildcard for file path for adding attachments
我想添加来自特定文件夹的附件。我指定了文件的路径和两个固定的关键字。
在 'filename2' 之后和 'pmonth' 之前还有更多的字符来完成文件路径,这些字符不固定,因此我需要使用通配符 (*)。
代码给出
'Couldn't find file'
我浏览了各种线程并尝试了解决方案。 None 为我想要的工作。
For ctr = 2 To lastrow
filename1 = Cells(ctr, 1).Value
filename2 = Cells(ctr, 3).Value
Set OutMail = OutApp.CreateItemFromTemplate(str_template)
path = "C:\Users\nikunj.v.tripathi\Desktop\" & filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
With OutMail
.Attachments.Add path ' <----- this line gives error
.To = Cells(ctr, 10).Value
.cc = Cells(ctr, 11).Value
.htmlbody = Replace(.htmlbody, "#Month#", smonth)
.htmlbody = Replace(.htmlbody, "#CLIENT NAME#", Cells(ctr, 1).Value
.Save
End With
Next ctr
要在这种情况下有效地使用 Dir 函数,您需要将路径和文件名作为两个单独的变量。假设您添加了另一个名为文件名的变量,那么您可以使用以下代码...
...
path = "C:\Users\nikunj.v.tripathi\Desktop\"
filename = filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
...
filename = Dir(path & filename) ' Dir returns the filename of the first file matching
' the criteria, or returns an empty string if no match.
Do Until filename = ""
.Attachments.Add path & filename
filename = Dir ' Using Dir again returns the next file matching
' the criteria, or returns an empty string if no match.
Loop
当然 - Attachments.Add
添加单个附件和 returns Attachment
对象。它怎么可能添加多个附件?
您可以使用 Scripting.FileSystemObject
遍历文件夹中的所有文件并一次添加一个附件。看,例如
https://devblogs.microsoft.com/scripting/how-can-i-get-a-list-of-all-the-files-in-a-folder-and-its-subfolders/
我想添加来自特定文件夹的附件。我指定了文件的路径和两个固定的关键字。
在 'filename2' 之后和 'pmonth' 之前还有更多的字符来完成文件路径,这些字符不固定,因此我需要使用通配符 (*)。
代码给出
'Couldn't find file'
我浏览了各种线程并尝试了解决方案。 None 为我想要的工作。
For ctr = 2 To lastrow
filename1 = Cells(ctr, 1).Value
filename2 = Cells(ctr, 3).Value
Set OutMail = OutApp.CreateItemFromTemplate(str_template)
path = "C:\Users\nikunj.v.tripathi\Desktop\" & filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
With OutMail
.Attachments.Add path ' <----- this line gives error
.To = Cells(ctr, 10).Value
.cc = Cells(ctr, 11).Value
.htmlbody = Replace(.htmlbody, "#Month#", smonth)
.htmlbody = Replace(.htmlbody, "#CLIENT NAME#", Cells(ctr, 1).Value
.Save
End With
Next ctr
要在这种情况下有效地使用 Dir 函数,您需要将路径和文件名作为两个单独的变量。假设您添加了另一个名为文件名的变量,那么您可以使用以下代码...
...
path = "C:\Users\nikunj.v.tripathi\Desktop\"
filename = filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
...
filename = Dir(path & filename) ' Dir returns the filename of the first file matching
' the criteria, or returns an empty string if no match.
Do Until filename = ""
.Attachments.Add path & filename
filename = Dir ' Using Dir again returns the next file matching
' the criteria, or returns an empty string if no match.
Loop
当然 - Attachments.Add
添加单个附件和 returns Attachment
对象。它怎么可能添加多个附件?
您可以使用 Scripting.FileSystemObject
遍历文件夹中的所有文件并一次添加一个附件。看,例如
https://devblogs.microsoft.com/scripting/how-can-i-get-a-list-of-all-the-files-in-a-folder-and-its-subfolders/