Excel 带有word文档附件的VBA宏电子邮件

Excel 带有word文档附件的VBA宏电子邮件,excel,vba,Excel,Vba,我正在学习Excel VBA,我想将Excel中的数据替换为word文档,并通过每行相应的电子邮件发送给员工。目前我已经发过电子邮件,但我不知道如何最好地附加word文档,我有数百名员工。 谢谢你所做的一切 如果我理解了您的需求,下面的代码可能会有所帮助。请注意,如果过程名称为sendMail,您可能会遇到问题,因为该方法已存在于Excel中。在这个例子中,我使用了sendmails这个名字 Sub sendEmails() On Error GoTo Error_Handler Di

我正在学习Excel VBA,我想将Excel中的数据替换为word文档,并通过每行相应的电子邮件发送给员工。目前我已经发过电子邮件,但我不知道如何最好地附加word文档,我有数百名员工。 谢谢你所做的一切


如果我理解了您的需求,下面的代码可能会有所帮助。请注意,如果过程名称为sendMail,您可能会遇到问题,因为该方法已存在于Excel中。在这个例子中,我使用了sendmails这个名字

Sub sendEmails()
On Error GoTo Error_Handler
    Dim OApp As Object
    Dim OMail As Object
    Dim WApp As Object
    Dim WDoc As Object
    Dim strTempFile As String
    Dim strWDocPath As String
    Dim row As Long
    Dim col As Long
    
    ' Replace FULL_PATH_NAME with the full name, including the path, of the Word document
    ' to use as a template, e.g. C:\Users\Sam\Documents\SalaryConfirmation.docx.
    ' The template can contain placeholders, e.g. <name>, which will be matched
    ' with the corresponding field names in the Excel worksheet.
    strWDocPath = "FULL_PATH_NAME"
    
    ' Check cell B1 = <mail>
    If [B1] <> "<mail>" Then
        MsgBox "Expected value ""<mail>"" in cell B1", vbCritical, "Failed"
        Exit Sub
    ' Check there is mail to send
    ElseIf Cells(Rows.Count, 2).End(xlUp).row = 1 Then
        MsgBox "No mail to send", vbInformation, "Exit"
        Exit Sub
    ' Check Word document path
    ElseIf strWDocPath = "" Or Dir(strWDocPath) = "" Then
        MsgBox "Word document not found: """ & strWDocPath & """", vbCritical, "Failed"
        Exit Sub
    End If

    Set OApp = CreateObject("Outlook.Application")
    Set WApp = CreateObject("Word.Application")
    
    For row = 2 To Cells(Rows.Count, 2).End(xlUp).row
        ' Create Word document from template
        Set WDoc = WApp.Documents.Add(strWDocPath)
        
        ' Replace field placeholders in Word document with values from respective fields in Excel
        For col = 3 To [A1].End(xlToRight).Column
            If Left(Cells(1, col), 1) = "<" And Right(Cells(1, col), 1) = ">" Then
                WDoc.Content.Find.Execute _
                    FindText:=Cells(1, col), ReplaceWith:=Cells(row, col), Replace:=2
            End If
        Next
        
        ' Save Word document in Temp folder
        strTempFile = Environ("Temp") & "\SalaryConfirmation.docx"
        WDoc.SaveAs2 strTempFile
        WDoc.Close 0
        
        ' Create email and attach Word document
        Set OMail = OApp.CreateItem(0)
        With OMail
            .To = Cells(row, 2)
            .Subject = "Salary confirmation"
            .Attachments.Add strTempFile
        End With
        
        ' Send email
        OMail.Send
    Next
    
    ' Clean up
    WApp.Quit 0
    ChDir Environ("Temp")
    Kill Dir(strTempFile)

Error_Exit:
    Exit Sub
Error_Handler:
    If Not OApp Is Nothing Then
        If Not OMail Is Nothing Then
            OMail.Close 1
        End If
    End If
    
    If Not WApp Is Nothing Then
        WApp.Quit 0
    End If
    
    MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error"
    Resume Error_Exit
End Sub
子发送电子邮件()
关于错误转到错误处理程序
作为对象的Dim OApp
将OMail作为对象
作为对象的Dim WApp
作为对象的Dim WDoc
将strTempFile设置为字符串
将strWDocPath设置为字符串
暗排一样长
暗色如长
'用Word文档的全名(包括路径)替换全名
'用作模板,例如C:\Users\Sam\Documents\SalaryConfirmation.docx。
'模板可以包含占位符,例如将匹配的占位符
'与Excel工作表中相应的字段名。
strWDocPath=“完整路径名称”
'检查单元格B1=
如果[B1]”“那么
单元格B1中的MsgBox“预期值”“”“”,vbCritical,“失败”
出口接头
'检查是否有邮件要发送
ElseIf单元格(Rows.Count,2).End(xlUp).row=1
MsgBox“无需发送邮件”,vbInformation,“退出”
出口接头
'检查Word文档路径
ElseIf strWDocPath=“或Dir(strWDocPath)=”“然后
MsgBox“找不到Word文档:”&strWDocPath&“”,vbCritical,“失败”
出口接头
如果结束
设置OApp=CreateObject(“Outlook.Application”)
设置WApp=CreateObject(“Word.Application”)
对于行=2到单元格(Rows.Count,2).End(xlUp).row
'从模板创建Word文档
Set WDoc=WApp.Documents.Add(strWDocPath)
'将Word文档中的字段占位符替换为Excel中相应字段的值
对于col=3到[A1]。结束(xlToRight)。列
如果左(单元格(1,列),1)=“”,则
WDoc.Content.Find.Execute_
FindText:=单元格(1,列),替换为:=单元格(行,列),替换为:=2
如果结束
下一个
'将Word文档保存在临时文件夹中
strTempFile=Environ(“Temp”)和“\SalaryConfirmation.docx”
WDoc.SaveAs2 strTempFile
WDoc.0关闭
'创建电子邮件并附加Word文档
设置OMail=OApp.CreateItem(0)
与奥马尔
.To=单元格(第2行)
.Subject=“工资确认”
.Attachments.Add strTempFile
以
'发送电子邮件
OMail,发送
下一个
“清理
WApp.退出0
ChDir环境(“临时”)
Kill Dir(strTempFile)
退出时出错:
出口接头
错误\u处理程序:
如果不是,那么OApp什么都不是
如果不是,那么OMail什么都不是
奥梅尔,关闭1号
如果结束
如果结束
如果不是,那么WApp什么都不是
WApp.退出0
如果结束
MsgBox错误编号&“:”错误描述(&R),vbCritical,“错误”
恢复错误\u退出
端接头

您是否阅读了有关该项目的信息?此外,您的问题是什么还不清楚,因为标题/文本暗示了一个问题,代码注释可能暗示了其他问题。因此,请澄清并解释您的代码是如何工作的。对不起,您使用的是CreateObject方法,它通常是为通用对象分配(后期绑定)而设计的。此外,根据您的公司设置,.Send方法可能不起作用;如果这是你的意图,而你在那条线上出错了,我会和你的系统/管理人员谈谈。当然,上面的两条评论^谢谢你的帮助,因为我有语言问题,所以我的问题不清楚,但是你的回答是我需要的,非常感谢。
Sub sendEmails()
On Error GoTo Error_Handler
    Dim OApp As Object
    Dim OMail As Object
    Dim WApp As Object
    Dim WDoc As Object
    Dim strTempFile As String
    Dim strWDocPath As String
    Dim row As Long
    Dim col As Long
    
    ' Replace FULL_PATH_NAME with the full name, including the path, of the Word document
    ' to use as a template, e.g. C:\Users\Sam\Documents\SalaryConfirmation.docx.
    ' The template can contain placeholders, e.g. <name>, which will be matched
    ' with the corresponding field names in the Excel worksheet.
    strWDocPath = "FULL_PATH_NAME"
    
    ' Check cell B1 = <mail>
    If [B1] <> "<mail>" Then
        MsgBox "Expected value ""<mail>"" in cell B1", vbCritical, "Failed"
        Exit Sub
    ' Check there is mail to send
    ElseIf Cells(Rows.Count, 2).End(xlUp).row = 1 Then
        MsgBox "No mail to send", vbInformation, "Exit"
        Exit Sub
    ' Check Word document path
    ElseIf strWDocPath = "" Or Dir(strWDocPath) = "" Then
        MsgBox "Word document not found: """ & strWDocPath & """", vbCritical, "Failed"
        Exit Sub
    End If

    Set OApp = CreateObject("Outlook.Application")
    Set WApp = CreateObject("Word.Application")
    
    For row = 2 To Cells(Rows.Count, 2).End(xlUp).row
        ' Create Word document from template
        Set WDoc = WApp.Documents.Add(strWDocPath)
        
        ' Replace field placeholders in Word document with values from respective fields in Excel
        For col = 3 To [A1].End(xlToRight).Column
            If Left(Cells(1, col), 1) = "<" And Right(Cells(1, col), 1) = ">" Then
                WDoc.Content.Find.Execute _
                    FindText:=Cells(1, col), ReplaceWith:=Cells(row, col), Replace:=2
            End If
        Next
        
        ' Save Word document in Temp folder
        strTempFile = Environ("Temp") & "\SalaryConfirmation.docx"
        WDoc.SaveAs2 strTempFile
        WDoc.Close 0
        
        ' Create email and attach Word document
        Set OMail = OApp.CreateItem(0)
        With OMail
            .To = Cells(row, 2)
            .Subject = "Salary confirmation"
            .Attachments.Add strTempFile
        End With
        
        ' Send email
        OMail.Send
    Next
    
    ' Clean up
    WApp.Quit 0
    ChDir Environ("Temp")
    Kill Dir(strTempFile)

Error_Exit:
    Exit Sub
Error_Handler:
    If Not OApp Is Nothing Then
        If Not OMail Is Nothing Then
            OMail.Close 1
        End If
    End If
    
    If Not WApp Is Nothing Then
        WApp.Quit 0
    End If
    
    MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error"
    Resume Error_Exit
End Sub