excel vba - 包含()的自定义公式

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

excel vba - custom formula for Contains()

excelvbaexcel-vbascripting

提问by toop

If i had a column like:

如果我有一个像这样的专栏:

ColumnA
-------
NUMBER
VARCHAR(50 BYTE)
TIMESTAMP

I'm looking for a vba function that would work like so:

我正在寻找一个可以像这样工作的 vba 函数:

contains("string to search for", cell to search it in) ie. =contains("VARCHAR",A2) and if the cell does contain it (anywhere in the cell - doesn't have to start or end the cell) then populate the cell (that uses the function) with "T" else "F".

contains("string to search", cell to search in) 即。=contains("VARCHAR",A2) 并且如果单元格确实包含它(单元格中的任何位置 - 不必开始或结束单元格)然后用“T”填充单元格(使用该函数)否则“F ”。

so in my example:

所以在我的例子中:

ColumnB
-------
F
T
F

Also could I then use this function inside other VBA code like so:

我也可以在其他 VBA 代码中使用这个函数,如下所示:

If Len(A2) > 10 and contains("CHAR",A2) Then
 //do stuff
End If

If they have to be separate functions (to use in cells returning "T"/"F" and to use in other VBA code), please provide both.

如果它们必须是单独的函数(在返回“T”/“F”的单元格中使用并在其他 VBA 代码中使用),请提供两者。

回答by Alex K.

You want VBA's InStr

你想要 VBA InStr

For example in a module;

例如在一个模块中;

Public Function Contains(Text As String, Cell As Range) As String
   If InStr(1, Cell.Value, Text, vbTextCompare) Then '//case insensitive
       Contains = "T"
   Else
       Contains = "F"
   End If
End Function

Enables =Contains("blah", A1)in a worksheet

=Contains("blah", A1)在工作表中启用