简体   繁体   中英

Excel Function or VBA code to search for number in comma-separated string

In a column that contains comma separated numbers entered by users:

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

I need to search for a specific number in each list, for example "1" and return TRUE in a Conditional Formatting rule to highlight that cell. However, everything I've tried returns true for any occurrence of the number such as 11, 12, 21, 100 and so on not just 1. I need it to only return TRUE when a specific number between the commas exists.

I need it to only return TRUE when a specific number between the commas exists.

You can create UDF as below

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

See image for reference.

在此处输入图片说明

For details on UDF see this .

Try something like the code below (explanation inside the code comments):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM