excel - 循环遍历每一列

标签 excel vba

我正在尝试编写一个 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像这样的声明。这将滚动通过第二行中的单元格,所以我猜你需要添加另一个循环来滚动所有行,一旦你有这个工作。

注意:我切换了TostrTo因为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/

相关文章:

php - 使用 PHP 在 Excel 工作表中显示长度为 10 的 BigInt 数据类型

excel - 使用 VBA 在远程桌面上打开文件

excel - 为什么Excel在VBA代码的公式中添加@?

vba - 更改 VBA 中的小数点分隔符(不仅在 Excel 中)

c# - 将 Excel 转换为内存流并通过 AngularJS 下载

excel - 计算列中的非空白文本单元格

excel - 根据左列单元格组合相邻行单元格

Excel VBA 脚本动态添加系列到图表

excel - Outlook 项目更改重复

sql - 在 Excel 数据连接中使用 VBA 更改命令文本 SQL 时收到运行时错误 (1004)