寻找Outlook以根据IF语句生成的数据发送电子邮件

时间:2019-04-18 14:13:23

标签: excel vba outlook

我知道还有其他关于同一件事的文章,但是我无法使其与我的变量一起使用。

我有2列数据使用IF语句,这些语句是IF(Asus!C:C=TODAY(),"Promo Today","")。我想使用VBA来检测单元格何时变成"Promo Today"并向收件人发送电子邮件(据我所知,电子邮件地址必须在单元格中定义,如我将在代码中看到的那样) ,我试图将其纳入其中。)

我尝试在代码中定位的第2列和第3列是IF语句所在的列,我没有考虑到这一点,只是在考虑是否要定位还行吗?

Private Sub Worksheet_Change()
Dim sEmailBodyp1 As String
Dim sEmailSubject As String
Dim sEmailTo As String
Dim Outlook As Object
Dim MasterCheck As Worksheet

sEmailTo = MasterCheck.Range("D2").Value
sEmailSubject = MasterCheck.Range("E2").Value
sEmailBodyp1 = MasterCheck.Range("F2").Value

If Target.Column = 2 And Target.Value = "Promo Today" Then
        With CreateObject("Outlook.Application").CreateItem(0)
            .To = sEmailTo
            .Subject = sEmailSubject
            .Body = sEmailBodyp1
            .Send
        End With
    End If


End Sub

2 个答案:

答案 0 :(得分:1)

简报

在VBA上,有几种访问Sheet的方法,最常见的方法是:

  • 工作表名称,您可以在Excel Sheet上进行设置(用户可以更改此名称)

enter image description here

然后像这样调用您的代码:

Dim myWorksheet As Worksheet   
Set myWorksheet = Worksheets("Sheet1") 'The user defined Excel sheet name.

  • Microsoft Excel对象表(可以在左窗格中找到)

enter image description here

您可以简单地这样称呼它(假设它的名字是Sheet1):

Sheet1.Activate

您的代码

因此,回到您的代码,由于变量MasterCheck未进行初始化,因此我们可以使用第一种方法并初始化其值:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim sEmailBodyp1 As String
    Dim sEmailSubject As String
    Dim sEmailTo As String
    Dim Outlook As Object
    Dim MasterCheck As Worksheet

    Set MasterCheck = Sheets("MySheet") 'Change "MySheet" with your sheet name

    sEmailTo = MasterCheck.Range("D2").Value
    sEmailSubject = MasterCheck.Range("E2").Value
    sEmailBodyp1 = MasterCheck.Range("F2").Value

    If Target.Column = 2 And Target.Value = "Promo Today" Then
        With CreateObject("Outlook.Application").CreateItem(0)
            .To = sEmailTo
            .Subject = sEmailSubject
            .Body = sEmailBodyp1
            .Send
        End With
    End If

End Sub

答案 1 :(得分:0)

类似的事情应该起作用:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Range("B:B")) Is Nothing Or Target.Cells.Count > 1 Then Exit Sub

    Dim sEmailBodyp1 As String
    Dim sEmailSubject As String
    Dim sEmailTo As String
    Dim Outlook As Object
    Dim MasterCheck As Worksheet

    Set MasterCheck = ActiveWorkbook.Sheets("SheetName") 'Change this with your sheet name

    sEmailTo = MasterCheck.Range("D2").Value
    sEmailSubject = MasterCheck.Range("E2").Value
    sEmailBodyp1 = MasterCheck.Range("F2").Value

    If Target.Value = "Promo Today" Then
        With CreateObject("Outlook.Application").CreateItem(0)
            .To = sEmailTo
            .Subject = sEmailSubject
            .Body = sEmailBodyp1
            .Send
        End With
    End If

End Sub