如果电子邮件主题行以某些值开头,则执行某些操作

If email subject line starts with certain values then do something

这行代码有什么问题?抛出 运行-时间错误“13”,类型不匹配。

Dim mail As Outlook.MailItem

If mail.Subject Like "VEH" & "*" Or "MAT" & "*" Then

试图说明电子邮件的主题是否以 "VEH" 或 "MAT" 开头,然后做一些事情。

您可以在这里简单地使用 VBA LEFT 函数:

If UCASE(LEFT(TRIM(mail.Subject), 3)) = "VEH" OR UCASE(LEFT(TRIM(mail.Subject), 3)) = "MAT" Then

'' DO something here

End If

If 语句的正确语法是:

If (mail.Subject Like "VEH*") Or (mail.Subject Like "MAT*") Then  

括号是可选的(Like 运算符的优先级高于 Or),但它更易于阅读。

如果电子邮件来自不同的用户,那么我不建议在这种情况下使用 Like。如果它是机器生成的并带有固定的 Subject 那么它就有意义了。

原因Like/Left区分大小写

例子:

Sub Sample()
    Dim s As String

    s = "vehicle"

    If s Like "VEH*" Then
        MsgBox "Found a match"
    Else
        MsgBox "didn't find a match"
    End If
End Sub

Sub Sample()
    Dim s As String

    s = "vehicle"

    If Left(s, 3) = "VEH" Then
        MsgBox "Found a match"
    Else
        MsgBox "didn't find a match"
    End If
End Sub

备选

对于不区分大小写的搜索,例如 VehiclevehicleVeHiCle,修改@PareshJ 发布的内容。

Sub Sample()
    Dim subj As String

    subj = "   Vehicle Number XYZ"

    If UCase(Left(Trim(subj), 3)) = "VEH" Then
        MsgBox "Found a match"
    Else
        MsgBox "didn't find a match"
    End If
End Sub

Trim 去除前导和尾随空格,Ucase 将字符串转换为大写。

编辑

如果您仍想使用 Like 那么您可能想使用这个

Option Compare Text '<~~ For case insensitive

Sub Sample()
    Dim subj As String

    subj = "   Vehicle Number XYZ"

    If Trim(subj) Like "VEH*" Then
        MsgBox "Found a match"
    Else
        MsgBox "didn't find a match"
    End If
End Sub

注意: Option Compare Text 也会影响代码中的任何其他比较。