简体   繁体   English

如何使用Excel VBA发送电子邮件

[英]How to send email using excel VBA

I have data contained in column A to H. The data in column A are email addresses. 我的A到H列中包含数据。A列中的数据是电子邮件地址。 I put a check box in another cell. 我在另一个单元格中放置了一个复选框。 What I want is when I tick the check box it proceeds to send email to the email account placed in last row column A. But the below code only works for cell A1. 我想要的是,当我勾选复选框时,它将继续发送电子邮件到位于最后一行A列的电子邮件帐户。但是下面的代码仅适用于单元格A1。

Private Sub CheckBox1_Click()

    Dim Email As String

    Row = 1
    Email = Sheet1.Cells(Row, 1)
    Do Until Sheet1.Cells(Row, 1) = ""
        Row = Row + 1
    Loop

    Dim OutApp As Object, OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    On Error Resume Next
    With OutMail
        .To = Email
        .Subject = score
        .HTMLBody = "This is a contain of Email Message"
        .Send
    End With
    On Error GoTo 0
    Set OutMail = Nothing

End Sub

In your section below, where you are trying to get the last row and then the email from that cell: 在下面的部分中,您尝试在其中获取最后一行,然后获取该单元格中的电子邮件:

Row = 1
Email = Sheet1.Cells(Row, 1)
Do Until Sheet1.Cells(Row, 1) = ""
    Row = Row + 1
Loop

you are taking the Email from the first row, and after in the Do Until loop you are checking for the last row, but not modifying the Email variable. 您从第一行获取Email ,然后在Do Until循环中检查最后一行, 但不修改 Email变量。

Resolve : There is no need to have a loop to find the last row with a valid email address in Column A, you can simply find it with the following lines below: 解决 :无需循环即可在A列中找到具有有效电子邮件地址的最后一行,您只需在下面的几行中即可找到它:

Dim LastRow As Long

' get last row with data in Column A (don't skip blank cells in the middle)
LastRow = Sheet1.Range("A1").End(xlDown).Row
Email = Sheet1.Range("A" & LastRow).Value

The rest of your code works just fine. 您的其余代码工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM