Excel函数或VBA代码在逗号分隔的string中search数字

在包含逗号分隔的数字的用户input的列中:

1,2,3,4,5 11,12,14,3 21,32,45,92,101,1 100,234,125,5 

我需要在每个列表中search特定的数字,例如“1”,并在条件格式规则中返回TRUE以突出显示该单元格。 但是,我试过的所有东西都返回true,如11,12,21,100等等,不只是1.我需要它只在逗号之间存在一个特定的数字时才返回TRUE。

我需要它只在逗号之间的特定数字存在时才返回TRUE。

您可以按如下所示创buildUDF

 Function CheckOne(rng As Range, chkValue As Long) As Boolean Dim n For Each n In Split(rng.Value, ",") If CLng(n) = chkValue Then CheckOne = True Exit For End If Next n End Function 

看图像以供参考。

在这里输入图像说明

有关UDF详细信息,请参阅此 。

尝试下面的代码(代码注释中的解释):

 Option Explicit Sub HighlightOnes() Dim i As Long Dim Elem As Variant Dim myArr As Variant With Worksheets("Sheet1") ' change "Sheet1" to your hseet's name For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row ' loop until last row with data in column A myArr = Split(.Range("A" & i).Value, ",") ' loop through array elements and look for 1 For Each Elem In myArr If Elem Like "1" Then ' check if current element is "1" .Range("B" & i).Value = "True" ' put a value of "True" in the next column (just for example) ' or proceed here with the formatting of the cell Exit For End If Next Elem Next i End With End Sub