VBA,如果字符串包含某个字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24617278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA, if a string contains a certain letter
提问by JahKnows
I do not usually work with VBA
and I cannot figure this out. I am trying to determine whether a certain letter is contained within a string on my spreadhseet.
我通常不与之合作VBA
,我无法弄清楚这一点。我试图确定某个字母是否包含在我的电子表格上的字符串中。
Private Sub CommandButton1_Click()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))
MsgBox RowCount
For i = 2 To RowCount
myString = Trim(Cells(i, 1).Value)
If myString.Contains("A") Then
oldStr = Cells(i, 15).Value
newStr = Left(oldStr, oldStr.IndexOf("A"))
End If
Next
End Sub
This code should go through a list of values and if it encounters the letter A to remove it and everything that comes after it. I am getting problems at my IF
statement, Invalid Qualifier. How would I be able to make my IF
statement output whether or not the String in the cell contains the letter A?
这段代码应该遍历一个值列表,如果遇到字母 A 将删除它以及它后面的所有内容。我在IF
声明无效限定符时遇到问题。IF
无论单元格中的字符串是否包含字母 A,我如何才能使语句输出?
Thank you very much
非常感谢
回答by Mark Balhoff
Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
尝试使用 InStr 函数,该函数返回字符串中找到该字符的索引。如果 InStr 返回 0,则未找到该字符串。
If InStr(myString, "A") > 0 Then
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
对于分配给 newStr 的行上的错误,也将 oldStr.IndexOf 转换为该 InStr 函数。
Left(oldStr, InStr(oldStr, "A"))
回答by sous2817
Not sure if this is what you're after, but it will loop through the range that you gave it and if it finds an "A" it will remove it from the cell. I'm not sure what oldStr is used for...
不确定这是否是您所追求的,但它会遍历您提供的范围,如果找到“A”,它将从单元格中删除它。我不确定 oldStr 用于什么...
Private Sub foo()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))
For i = 2 To RowCount
myString = Trim(Cells(i, 1).Value)
If InStr(myString, "A") > 0 Then
Cells(i, 1).Value = Left(myString, InStr(myString, "A"))
End If
Next
End Sub
回答by PowerUser
Try:
尝试:
If myString like "*A*" Then
回答by user3810910
If you are looping through a lot of cells, use the binary function, it is much faster. Using "<> 0" in place of "> 0" also makes it faster:
如果您要遍历很多单元格,请使用二元函数,它会快得多。使用“<> 0”代替“> 0”也可以使它更快:
If InStrB(1, myString, "a", vbBinaryCompare) <> 0