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

时间:2015-06-03 07:33:36

标签: excel excel-vba outlook vba

这行代码有什么问题?抛出运行时错误' 13',输入错误匹配。

Dim mail As Outlook.MailItem

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

试图说明电子邮件的主题是否以" VEH"或者" MAT"然后做点什么。

3 个答案:

答案 0 :(得分:3)

您可以在此处使用VBA LEFT功能:

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

'' DO something here

End If

答案 1 :(得分:2)

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

原因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也会影响代码中的任何其他比较。

答案 2 :(得分:1)

If语句的正确语法是:

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

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