提问人:colemaaz 提问时间:11/11/2023 最后编辑:Communitycolemaaz 更新时间:11/13/2023 访问量:83
使用 Excel VBA 向电子邮件正文添加范围
Add a range to email body with Excel VBA
问:
我正在尝试使用 Excel VBA 通过 Outlook 发送电子邮件。
我在网上找到了代码,并输入了自己的价值观。
我明白了
运行时错误“13”“类型不匹配”。
我正在尝试向电子邮件正文添加一个范围。原始代码添加了单个单元格的值。
Sub SendEmails()
Dim OutApp As Object
Dim OutMail As Object
Dim ws As Worksheet
Dim LastRow As Long
Dim i As Long
' Create a reference to the Outlook application
Set OutApp = CreateObject("Outlook.Application")
' Set the worksheet where your data is located
Set ws = ThisWorkbook.Sheets("Sheet3") ' Change "Sheet2" to your sheet name
' Find the last row with data in column A
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Loop through each row with data
For i = 2 To LastRow ' Assuming the header is in row 1
' Create a new email
Set OutMail = OutApp.CreateItem(0)
' Set email properties
With OutMail
' Set the email address from Column D
.To = ws.Cells(73, 12).Value
' Set the subject with the Invoice ID from Column A
.Subject = "Approval Requested - " & ws.Cells(1, 2).Value
' Create the email body with the requested information
.Body = "Hi, " & ws.Cells(73, 11).Value & vbNewLine & vbNewLine & _
"Please kindly approve the expenses below for ws.cells(1, 2).value on the ws.cells(73, 13).value tour. Thank you!" & vbNewLine & vbNewLine & _
ws.Range("h73:i100") & vbNewLine & vbNewLine & _
"Best Regards," & vbNewLine & "Aaron"
' Send the email
.Send
End With
' Release the email object
Set OutMail = Nothing
Next i
' Release the Outlook application object
Set OutApp = Nothing
End Sub
答:
0赞
Nick Abbot
11/11/2023
#1
如果你想在你的身体中包括这个范围,那就试试这个。它很丑,但它有效:
Dim h73i100 As String
Dim iRow As Long
iRow = 73
For Each c In Range("h73:i100").Cells
If c.Row = iRow Then
h73i100 = h73i100 & c.Value & vbTab
Else
h73i100 = h73i100 & vbCrLf & c.Value & vbTab
iRow = c.Row
End If
Next
然后添加到您的 .身体:h73i100
.Body = "Hi, " & ws.Cells(73, 11).Value & vbNewLine & vbNewLine & _
"Please kindly approve the expenses below for ws.cells(1, 2).value on the ws.cells(73, 13).value tour. Thank you!" & vbNewLine & vbNewLine & _
h73i100 & vbNewLine & vbNewLine & _
"Best Regards," & vbNewLine & "Aaron"
0赞
Dmitry Streblechenko
11/11/2023
#2
替换为 。ws.Range("h73:i100")
ws.Range("h73:i100").Text
评论
0赞
Dmitry Streblechenko
11/11/2023
Text
对于具有多个单元格的范围,将返回第一个单元格的文本。如果该单元格为空或不是文本,则返回 null。要支持多个单元格,请使用 - 您将获得该范围内所有单元格的数组(行在前)。您有责任正确格式化它。另请参阅 Nick Abbot 的答案ws.Range("h73:i100").Value2
评论
ws.Range("h73:i100")