多个收件人电子邮件在VBA中不匹配

时间:2013-11-13 13:57:40

标签: excel vba email excel-vba

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

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

但是,我一直收到不匹配错误,我不知道如何解决它。

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

请原谅我,我是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

知道为什么会这样吗?

1 个答案:

答案 0 :(得分: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