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

[英]If email subject line starts with certain values then do something


What is wrong with this line of code? Throws up Run-time error '13', Type mis-match.

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

Dim mail As Outlook.MailItem

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

Trying to say if the subject of the email starts with "VEH" or "MAT", then do something.

试着说电子邮件的主题是以“VEH”还是“MAT”开头,然后做点什么。

3 个解决方案

#1


1  

The correct syntax for your If statement is:

If语句的正确语法是:

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

The brackets are optional (Like operator has higher precedence than Or), but it's easier to read.

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

#2


3  

You can simply use VBA LEFT function here:

你可以在这里简单地使用VBA LEFT功能:

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

'' DO something here

End If

#3


2  

If the emails are from different users then I wouldn't recommend using Like in such a scenario. If it is machine generated with fixed Subject then it makes sense.

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

Reason: Like/Left is case sensitive

原因:Like / Left区分大小写

Example:

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

or

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

Alternative

For a search which is not case sensitive for example Vehicle, vehicle, VeHiCle, modify what @PareshJ posted.

对于不区分大小写的搜索,例如Vehicle,vehicle,VeHiCle,修改@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 trims the leading and trailing spaces and Ucase converts a string into uppercase.

修剪修剪前导和尾随空格,Ucase将字符串转换为大写。

Edit

If you still want to use Like then you may want to use this

如果你仍想使用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

Caution: Option Compare Text will also affect any other comparisons in the code.

警告:选项比较文本也会影响代码中的任何其他比较。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/06/03/6f846b12ca2c59297bd6dc59208764cd.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告