VBA:案件不知情,如果单元格=string

在这个例子中,我想删除一个string的结尾,如果它包含bk,BK,Bk或bK。 有没有简单的方法来使这个案件不知情? 谢谢

If Right(Cells(i, 1), 2) = "bk" Then Cells(i, 1) = Replace(Cells(i, 1), "bk", "") End If 

要删除只有最后两个字符,我build议:

 If UCase(R) Like "*bk" Then R = Left(R, Len(R) - 2) 

其中R是范围对象(或文本string)

是的,因为你想在string末尾replace各种“bk”,你可以使用UCase ,就像下面的代码一样:

 If UCase(Right(Cells(i, 1), 2)) = "BK" Then Cells(i, 1) = Replace(Cells(i, 1), "bk", "", 1, -1, vbTextCompare) End If 

注意 :将vbTextCompare的最后一个参数添加到Replace函数中,表明它不区分大小写,并将删除各种“bk”。

编辑1 :如果您在某个string中出现了多个“bk”,而您只想删除string末尾的那个,请使用下面的代码(感谢@Ron Rosenfeld):

 If UCase(Right(Cells(i, 1), 2)) = "BK" Then Cells(i, 1) = Left(Cells(i, 1), Len(Cells(i, 1)) - 2) End If