在IF语句中应用userform答案

时间:2017-05-18 20:07:40

标签: vba if-statement outlook userform

我正在尝试实现一个IF语句,以便为HTML正文,主题等添加不同的用户答案(如sTitle和sSurename)。代码总是转到第二个选项,没有错误。

看起来当我有一个空的电子邮件时,我看到了签名,但当我在Body中更新任何内容时,签名消失了。

Sub template()

    Dim myItem As Outlook.MailItem
    Dim strContact As String
    Dim strHTML As String

    Dim sType As String
    Dim sTitle As String
    Dim sName As String
    Dim sSurname As String
    Dim sExpirydate As String
    Dim sGender As String

    With UserForm1

        sType = .ComboBox1.Value
        sTitle = .ComboBox2.Value
        sName = .TextBox1.Value
        sSurname = .TextBox2.Value
        sExpirydate = .TextBox3.Value
        sGender = .ComboBox3.Value

    End With

    Set myItem = CreateItem(olMailItem)
    strHTML = myItem.HTMLBody

    With myItem
        .BodyFormat = olFormatHTML

        If sType = "New" Then
            .HTMLBody = "<HTML><BODY><b>Dear " & sTitle & " " & sSurname & "</b> 111 the message text here.  </BODY></HTML>"
            .Subject = "New case"
        Else
            .HTMLBody = "<HTML><BODY><b>Dear " & sTitle & " " & sSurname & "</b> 222 the message text here.  </BODY></HTML>"
            .Subject = "Old case"
        End If  

        .OriginatorDeliveryReportRequested = True
        .ReadReceiptRequested = True

    End With

    myItem.Display

End Sub

Userform:

Private Sub TextBox1_Change()

End Sub

Private Sub TextBox2_Change()

End Sub

Private Sub TextBox3_Change()

End Sub

Private Sub UserForm_Initialize()

UserForm1.StartUpPosition = 2

With ComboBox1
    .AddItem "New"
    .AddItem "Renewal"    
End With

With ComboBox2
    .AddItem "Mr"
    .AddItem "Miss"
    .AddItem "Mrs"
    .AddItem "Ms"
End With

With ComboBox3
    .AddItem "You"
    .AddItem "He"
    .AddItem "She" 
End With

End Sub


Private Sub CommandButton1_Click()

    If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or ComboBox1 = "" Or ComboBox2 = "" Or ComboBox3 = "" Then
        MsgBox ("Fill in all Boxes")

        Exit Sub
    End If
    Unload Me

template
End Sub

1 个答案:

答案 0 :(得分:0)

根据您ComboBox1的初始化判断,我认为您正在测试If语句中的错误值。您可能应该测试"New"

,而不是测试"Form1"

您也有一个拼写错误,因为您声明了一个名为sSurname的变量,但之后您使用了sSurename。 (sExpirydate存在类似问题。)高度建议您将Option Explicit作为每个代码模块的第一行,这会强制您声明所有变量。这样,诸如此类的拼写错误就会在编译时而不是在运行时被捕获。

'...
sSurname = .TextBox2.Value
sExpirydate = .TextBox3.Value    
'...
'...
If sType = "Form1" Then
    .HTMLBody = "<HTML><BODY><b>Dear " & sTitle & " " & sSurname & "</b> 111 the message text here.  </BODY></HTML>"
    .Subject = "New case"
Else
    .HTMLBody = "<HTML><BODY><b>Dear " & sTitle & " " & sSurname & "</b> 222 the message text here.  </BODY></HTML>"
    .Subject = "Old case"
End If