动态确定的单元格的返回值

时间:2018-03-28 08:55:32

标签: vba excel-vba excel

下面的代码验证“Sheet1”中的A列是否与“Sheet2”中的A列具有相同的值。如果是这样,则应从B栏“Sheet2”中获取电子邮件地址。

我的问题是从“Sheet2”列B获取电子邮件地址。

Sub mail()

    Dim A As Long
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim wb As Workbook
    Dim check

    Set wb = Excel.ActiveWorkbook
    Set sh1 = wb.Worksheets(1)
    Set sh2 = wb.Worksheets(2)
    Application.ScreenUpdating = False

    For A = 2 To sh1.Cells(Rows.Count, "A").End(xlUp).Row

        check = Application.match(sh1.Cells(A, 1).Value, sh2.Columns(1), 0)

        If IsError(check) Then
            MsgBox "No email was found!"
        Else
            ' i am not able to set this.
            'h = take the email address from sheet2 column B

            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.createItem(olmailitem)
            Set wb2 = ActiveWorkbook
            ActiveWorkbook.Save

            With OutMail
                .Display
                .To = h ' attached the email address
                .cc = ""
                .BCC = ""
                .Subject = "Test - " '& B & " " & F
                .htmlbody = "<p style='font-family:calibri;font-size:15'>" & "Hi " & C & "<BR/>" & "<BR/>" & "Please check the attached template." & "<br/>" & "<BR/>" & "Change data if required." & "<BR/>" & "<br/>" & "This e-mail has been automatically send! " & "<br/>" & "<br/>" & "With best regards," & "<br/>" & "<br/>" 
                .attachments.Add wb2.FullName
            End With

            ActiveWorkbook.Close              
        End If

    Next

End Sub

1 个答案:

答案 0 :(得分:2)

在“PEH”的帮助下,我成功找到了解决方案:

Sub mail()

    Dim A As Long
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim wb As Workbook

    Dim check

    Set wb = Excel.ActiveWorkbook
    Set sh1 = wb.Worksheets(1)
    Set sh2 = wb.Worksheets(2)

    For A = 2 To sh1.Cells(Rows.Count, "A").End(xlUp).Row
        check = Application.match(sh1.Cells(A, 1).Value, sh2.Columns(1), 0)

        If IsError(check) And Not IsEmpty(sh1.Cells(A, 1)) Then
            MsgBox "No email was found!"
        Else
            h = sh2.Cells(check, 2).Value


            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.createItem(olmailitem)
            Set wb2 = ActiveWorkbook
            wb.Save

            With OutMail
                .Display
                .To = h
                .cc = ""
                .BCC = ""
                .Subject = "Test - " '& B & " " & F
                .htmlbody = "<p style='font-family:calibri;font-size:15'>" & "Hi " & C & "<BR/>" & "<BR/>" & "Please check the attached template." & "<br/>" & "<BR/>" & "Change data if required." & "<BR/>" & "<br/>" & "This e-mail has been automatically send! " & "<br/>" & "<br/>" & "With best regards," & "<br/>" & "<br/>"
                .attachments.Add wb2.FullName
            End With

            wb.Close
        End If
Next

End Sub