【问题标题】:Excel VBA - email subject line to include value of offset cellExcel VBA - 电子邮件主题行包含偏移单元格的值
【发布时间】:2019-10-12 02:52:29
【问题描述】:

我是 VB 的新手,希望能提供任何帮助。提前谢谢你。

我正在尝试在特定单元格具有特定值时发送电子邮件。例如,当单元格 E3 的值为 1 时,我想发送电子邮件 1,当它的值为 2 时,我想发送电子邮件 2。这部分工作正常。我还希望主题行是左侧3个单元格的内容,即当单元格E3被触发发送电子邮件时,我希望主题行是B3的内容,当E4被触发时,我想要以B4的内容为准。这是我失误的地方,我尝试了各种偏移量和范围选项,但我只是在电子邮件中得到一个空白主题行。这就是我所拥有的:

Dim xRg As Range
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Target.Cells.Count > 1 Then Exit Sub
  Set xRg = Intersect(Range("E3:E5"), Target)
    If xRg Is Nothing Then Exit Sub
    If IsNumeric(Target.Value) And Target.Value = 1 Then
        Call Mail_small_Text_Outlook
    ElseIf IsNumeric(Target.Value) And Target.Value = 2 Then
        Call Mail_small_Text_Outlook2
        End If
End Sub
Sub Mail_small_Text_Outlook()
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Good Day" & vbNewLine & _
              "Content Mail 1"
    On Error Resume Next
    With xOutMail
        .To = "xxx@mci.co.za"
        .CC = ""
        .BCC = ""
        .Subject = ActiveCell.Offset(0, -3).Value
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub
Sub Mail_small_Text_Outlook2()
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Good Day" & vbNewLine & _
              "Content Mail 2"
    On Error Resume Next
    With xOutMail
        .To = "xxx@mci.co.za"
        .CC = ""
        .BCC = ""
        .Subject = ActiveCell.Offset(0, -3).Value
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub

【问题讨论】:

  • 查看是否可以在 With.. End With 构造之前捕获 ActiveCell.Offset(0, -3).Value 作为临时字符串。如果字符串为空,则可能是 ActiveCell 连接问题,或者数据类型/excelsheet/工作簿引用可能有误。

标签: excel vba


【解决方案1】:

我不使用 ActiveCell,而是将“Target”作为参数添加到 Mail_small_Text_Outlook。这样您就可以确定您引用的单元格是同一个单元格。

如果您需要使用 ActiveCell(出于某种原因)并且没有得到正确的结果,您可以使用类似:
MsgBox ActiveCell.Address
只是为了仔细检查您使用的单元格是否是您期望的单元格。

我还建议将Mail_small_Text_OutlookMail_small_Text_Outlook2 合并到一个子目录中,并添加一个参数来指定您要使用的电子邮件正文。这样,打开 Outlook 和创建实际电子邮件的代码只在一个地方,因此如果您需要更改/调试它,您只需执行一次。

最终的 sub 可能看起来像这样: Mail_small_Text_Outlook(Target As Range, EmailBody As Integer).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多