在目录中搜索 PDF 文件并使用 outlook 邮件发送

Search for a PDF file in directory and send with outlook Mail

我想根据以下条件创建 excel vba:

在目录中搜索 A1、A2 列...多个...中提到的名称的 PDF 文件,如果找到,则通过 outlook 发送该文件和搜索到的文件附件。如果找不到文件,请忽略该文件并移至下一个文件。

下面的 vba 我在 pfile = pfile + 1 处显示错误 "Type Mismatch" 并循环没有执行。让我知道哪里出错了

Sub CheckandSend()
Dim obMail As Outlook.MailItem
Dim irow As Integer
Dim dpath As String
Dim pfile As String

`'' directory that contains files

`dpath = "xxxx"

`'' loop through all files and send mail

irow = 1

Do While Cells(irow, 1) <> Empty

'' get file name in column A
pfile = Dir(dpath & "\*" & Cells(irow, 1) & "*")
'' check file exist and pdf file
If pfile <> "" And Right(pfile, 3) = "pdf" Then
    Set obMail = Outlook.CreateItem(olMailItem)

    With obMail
        .To = "xxx@domain.com"
        .Subject = "123"
        .BodyFormat = olFormatPlain
        .Body = "123"
        .Attachments.Add (dpath & "\" & pfile)
        .Send
    End With
    End If
pfile = pfile + 1
Loop
End Sub

pfile 是一个字符串。因此,如果您需要连接字符串,则需要改用 & 符号。

很可能您需要增加单元格数量,如下所示:

Do While Cells(irow, 1) <> Empty

 '' get file name in column A
 pfile = Dir(dpath & "\*" & Cells(irow, 1) & "*")
 '' check file exist and pdf file 
 If pfile <> "" And Right(pfile, 3) = "pdf" Then
  Set obMail = Outlook.CreateItem(olMailItem)

  With obMail
    .To = "xxx@domain.com"
    .Subject = "123"
    .BodyFormat = olFormatPlain
    .Body = "123"
    .Attachments.Add (dpath & "\" & pfile)
    .Send
  End With
 End If
 irow = irow + 1
Loop