在 IF 语句中应用用户表单答案

Apply userform answers in IF statement

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

另外,当我收到一封空电子邮件时,我会看到签名,但当我更新 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

用户表单:

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

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

而不是测试 "New"

您似乎也有打字错误,因为您声明了一个名为 sSurname 的变量,但随后却使用了 sSurename。 (sExpirydate 也存在类似的问题。)highly 建议您将 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