【问题标题】:multiple recipients email mismatch in VBAVBA中的多个收件人电子邮件不匹配
【发布时间】:2013-11-26 03:59:41
【问题描述】:

我正在尝试在一系列单元格中添加多个收件人的电子邮件。

我可以选择工作表上的电子邮件范围。

但是,我不断收到此不匹配错误,我不知道如何解决。

我一直在寻找解决方案并采取了相同的步骤。

请原谅我,我是 VBA 新手。 非常感谢您的帮助。 我的代码如下,

    Private Sub CommandButton1_Click()

        Dim olapp As Object
        Dim olmail As Object
        Dim recip As String


    lastr = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row 
    'this is for the range of data to be copied on the body but have yet to do it

    lastr2 = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 7).End(xlUp).Row


        recip = ThisWorkbook.Sheets("Sheet1").Range("G3:G" & lastr2).Value 
        'mismatch after this step

        Set olapp = CreateObject("Outlook.Application")

        Set olmail = olapp.CreateItem(0)

        With MItem
         .to = recip
         .Subject = "hello"
         .Body = "whats up"
         .display
         End With

知道为什么会这样吗?

【问题讨论】:

标签: vba email excel


【解决方案1】:

您正在尝试将一个数组(多个单元格的范围是一个数组)分配给一个字符串变量。无需测试,我知道您可以使用 For Each 循环解决此问题,正如 Jaycal 的评论所建议的:

Dim cl as Range
For each cl in ThisWorkbook.Sheets("Sheet1").Range("G3:G" & lastr2).Cells
    recip = recip & ";" & cl.Value    
Next

但您可以使用string Join function 进行简化。 Join 函数有效地在字符串数组上执行此循环,因此它为您节省了不必要的循环。我修改为使用范围变量以提高可读性:

Dim sendRange as Range
Set sendRange = ThisWorkbook.Sheets("Sheet1").Range("G3:G" & lastr2)
recip = Join(Application.Transpose(sendRange.Value), ";")

无论您使用哪种方法,您都可以使用相同的With 块。

    With MItem
     .to = recip
     .Subject = "hello"
     .Body = "whats up"
     .display
     End With

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2016-04-05
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多