2017-05-29 56 views
0

我有以下简单的Excel电子表格:VBA IF-条件电子邮件

A  B 
1 10 
2 20 

而且我用下面的VBA发送了一封邮件:

Sub Test_EMail4() 
    If ExitAll = False Then 
     Dim OApp As Object, OMail As Object, signature As String 
     Set OApp = CreateObject("Outlook.Application") 
     Set OMail = OApp.CreateItem(0) 
      With OMail 
      .Display 
      End With 
      signature = OMail.HTMLbody 
      With OMail 
      .To = "[email protected]" 
      .Subject = "test" 
      .HTMLbody = "<p> Permant Content goes here </p>" 
      If Sheet1.Range("A1").Value = 10 Then 
      .HTMLbody = "<p> Content if Formula is true </p>" 
      Else 
      End If 
      End With 
     Set OMail = Nothing 
     Set OApp = Nothing 
    Else 
    End If 
End Sub 

正如你所看到的,我在HTML-Body中有一个If-条件。 我想要实现第一个标记<p> Permanet content goes here </p>总是显示在电子邮件中,而第二个标记<p> Content if Formula is true </p>仅在满足IF-公式中的条件时才会显示(如本例中)

现在,它只显示电子邮件中IF-Formula内的内容。我怎样才能包含永久部分?

回答

0

刚刚建立消息的With OMail块这样的外:

Dim strBody As String 

strBody = "<p> Permant Content goes here </p>" 
If Sheet1.Range("A1").Value = 10 Then 
    strBody = strBody & "<p> Content if Formula is true </p>" 
End If 

然后设置strBodyHTMLbody根据您当前的代码:

Sub Test_EMail4() 

    Dim strBody As String 
    Dim OApp As Object, OMail As Object, signature As String 

    strBody = "<p> Permant Content goes here </p>" 
    If Sheet1.Range("A1").Value = 10 Then 
     strBody = strBody & "<p> Content if Formula is true </p>" 
    End If 

    If ExitAll = False Then 
     Set OApp = CreateObject("Outlook.Application") 
     Set OMail = OApp.CreateItem(0) 
     With OMail 
      .display 
     End With 
     signature = OMail.HTMLBody 
     With OMail 
      .To = "[email protected]" 
      .Subject = "test" 
      .HTMLBody = strBody 
     End With 
     Set OMail = Nothing 
     Set OApp = Nothing 
    Else 
    End If 

End Sub 
+0

嗨,罗宾,当我复制我的VBA中的两个代码时,我必须考虑一些事情吗?当我在VBA中键入它们时,我的电子邮件中没有显示任何内容。 – Michi

+0

看到我的编辑 - 希望有所帮助 - 包括你的原始代码在整个Sub的建议# –

+0

您好罗宾,当我把你的代码,我得到错误“对象需要(424)”。我试图在第一个代码周围放置一个Sub()... End Sub(),但它仍然不起作用。你知道我的错误在哪里吗? – Michi

0
从你把这个东西它解决了

。由于不需要imo,因此删除了Signature

Sub Test_EMail4() 
If ExitAll = False Then 
    Dim OApp As Object, OMail As Object 
    Set OApp = CreateObject("Outlook.Application") 
    Set OMail = OApp.CreateItem(0) 

     With OMail 
     .Display 
     .To = "[email protected]" 
     .Subject = "test" 
     If Sheet1.Range("A1").Value = 10 Then 
     .HTMLBody = "<p> Permant Content goes here </p>" & .HTMLBody 
     Else 
     .HTMLBody = "<p> Content if Formula is true </p>" & .HTMLBody 
     End If 
     End With 
     With OMail 
     .Display 'change to "send" 
     End With 

    Set OMail = Nothing 
    Set OApp = Nothing 
Else 
End If 
End Sub