Excel VBA 检查混合数据时单元格是否包含字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20461384/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:52:01  来源:igfitidea点击:

Excel VBA check if a cell contains a string when data is mixed

excel-vbavbaexcel

提问by Amatya

I have some data that contains both numeric and string values

我有一些包含数字和字符串值的数据

Name Code 

Bob   1

Alice 2

Bob   33AL

Dan   AFAL

Alert  AL99

Bob    ALP

I want to select names where the "Code" column contains "AL" somewhere.

我想选择“代码”列在某处包含“AL”的名称。

If I do

如果我做

 If InStr(0, Cells(j, Code_column).Value, "AL", vbTextCompare) <> 0 Then

then my loop doesn't run because of the numeric values at some points in the column.

那么我的循环不会因为列中某些点的数值而运行。

I have tried

我试过了

 If InStr(0, CStr(Cells(j, Code_column).Value), "AL", vbTextCompare) <> 0 Then

but I am getting the same error. What should I try? A pre-loop checking if it is numeric?

但我遇到了同样的错误。我应该尝试什么?预循环检查它是否是数字?

回答by brettdj

In code something like this for data in Columns A:Bof the active sheet

A:B活动表的列中的数据的代码中

You can do the same thing manually without code

您可以在没有代码的情况下手动执行相同的操作

Then in both cases work with the output (plus then reverse the logic for your second criteria)

然后在这两种情况下使用输出(加上然后反转第二个标准的逻辑)

Sub CookHooker()
Dim rng As Range
ActiveSheet.AutoFilterMode = False
Set rng1 = Range([a1], Cells(Rows.Count, "B").End(xlUp))
rng1.AutoFilter Field:=2, Criteria1:="=*AL*", Operator:=xlAnd
End Sub