我正在尝试编写一个 VBA 代码,它将自动将文档发送给多个收件人。我的 Excel 电子表格如下所示:
Name Report #1 Report #2 Report #3
Recipient Email 1 Email 1 Email 1
Email 2 Email 2 Email 2
Email 3 Email 3 Email 3
Email 4 Email 4
Email 5
该代码使用单元格 B1 查找报告名称并将其定位在驱动器上。然后将其作为附件发送给 B 列中的收件人。到目前为止,我已经能够做到这一点:
Option Explicit
Sub Email_Report()
'Purpose: AustrTomate sending of reports via email to a list of specified Recipients
Dim OutApp As Object
Dim OutMail As Object
Dim EmailRng As Range, Recipient As Range
Dim strTo As String
Set EmailRng = Worksheets("Sheets1").Range("B2:B20")
For Each Recipient In EmailRng
strTo = strTo & ";" & Recipient.Value
Next
strTo = Mid(strTo, 2)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.strTo = strTo
.CC = ""
.BCC = ""
.Subject = "Report Name Here"
.Body = "Body text here"
.Attachments.Add ("File location here")
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
但是我很难找到一个优雅的解决方案来让代码继续到列 C、D 等等来做同样的事情。谁能把我推向正确的方向?
最佳答案
尝试更换您的 For Each
像这样的声明。这将滚动通过第二行中的单元格,所以我猜你需要添加另一个循环来滚动所有行,一旦你有这个工作。
注意:我切换了To
至strTo
因为To
给了我一个错误。它是 VBA 中的保留关键字。
获取电子邮件的新循环:
For column = 2 To EmailRng.Cells.Count
If Cells(2, column) <> "" Then 'Don't bother cell is blank
'Don't add a semicolon with the first address
If strTo = "" Then
strTo = Cells(2, column)
Else
strTo = strTo & ";" & Cells(2, column)
End If
End If
Next
关于excel - 循环遍历每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30961118/