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

我想写一个If语句来满足条件,只用一个单词。 例如:

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

即使只有"quick"这个词,我想要发生的事情也会得到满足。

您可以使用InStr()函数来testing子string的string:

 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运算符来testing一个string是否包含一个子string:

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

请注意,这些方法也会匹配"quickly"和其他包含string"quick"单词。 如果你想得到更具体的,正则expression式可能会更好地工作。 添加对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