繁体   English   中英

语法:在excel-vba中使用IF语句

[英]Syntax: using IF statement in excel-vba

我想编写一个If语句,仅使用一个单词即可满足条件。 例如:

if sheet1.cells(1,1)="a quick brown fox" then
end if

我想发生的是,即使只有"quick"这个词,也可以满足条件。

您可以使用InStr()函数测试字符串是否为子字符串:

If InStr(Sheet1.Cells(1, 1), "quick") > 0 Then
    ' Cell contains the string "quick"
End If

对于不区分大小写的比较,必须为函数提供所有四个可能的参数:

If InStr(1, Sheet1.Cells(1, 1), "quick", vbTextCompare) > 0 Then
    ' Cell contains the string "quick" or "QUICK" or any combination of upper/lowercase
End If

就像@AndyG在下面的评论中提到的,您还可以将Like运算符与通配符一起使用,以测试字符串是否包含子字符串:

If Sheet1.Cells(1, 1) Like "*quick*" Then          ' Case-sensitive
-or-
If LCase$(Sheet1.Cells(1, 1)) Like "*quick*" Then  ' Case-insensitive

请注意,这些方法还将匹配"quickly"和其他包含字符串"quick"单词。 如果您想更具体一点,则正则表达式可能会更好。 添加对Microsoft VBScript Regular Expressions 5.5库的引用,您可以使用以下代码:

Dim re As New RegExp
re.IgnoreCase = False       ' Up to you
re.Pattern = "\bquick\b"    ' Match the word "quick"

If re.Test(Sheet1.Cells(1, 1)) Then
    ' Cell contains the word "quick"
End If

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM