【问题标题】:Wildcard for file path for adding attachments用于添加附件的文件路径的通配符
【发布时间】:2020-11-20 07:39:47
【问题描述】:

我想添加来自特定文件夹的附件。我指定了文件的路径和两个固定的关键字。

在“filename2”之后和“pmonth”之前有更多字符来完成文件路径,这些字符不固定,因此我需要使用通配符 (*)。

代码给出

'找不到文件'

我经历了各种线程并尝试了解决方案。没有一个适合我想要的。

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-command 并遍历它的结果。一个一个地附上文件。
  • 嗨@FunThomas,感谢您的回复,我以前从未使用过 Dir,所以您是否建议在指定路径或在 outmail 中调用它时使用 Dir?你能举个例子吗?

标签: vba outlook wildcard


【解决方案1】:

为了在这种情况下有效地使用 Dir 函数,您需要将路径和文件名作为两个单独的变量。假设您添加了另一个名为 filename 的变量,那么您可以使用以下代码...

...

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

【讨论】:

  • 嗨@Sam,您的代码运行良好。谢谢您的帮助。 :)
【解决方案2】:

当然 - Attachments.Add 添加单个附件并返回 Attachment 对象。怎么可能添加多个附件?

您可以使用Scripting.FileSystemObject 循环浏览文件夹中的所有文件并一次添加一个附件。见,例如 https://devblogs.microsoft.com/scripting/how-can-i-get-a-list-of-all-the-files-in-a-folder-and-its-subfolders/

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多