Excel VBA在Cell中查找编号

时间:2017-10-16 07:50:04

标签: excel vba

我们的列"跟随ID",其中包含格式为" 1的前辈的ID; 2; 3; 4&#34 ;.现在我想在特定单元格中找到ID。我的问题是,如果我f.e.搜索" 1",当有一个" 11,21,13,14,......时,它也是如此。在细胞内。有没有办法搜索" ID"在"跟随ID",当ID是另一个ID的一部分时没有变为真?

For i = 2 To 250
  Dim tmp As String
  tmp = ""
  If Cells(i, 1) = "" Then Exit For
  For j = 2 To 250
    If Cells(j, 1) = "" Then
      Exit For
    End If
    If Cells(j, 11) = Cells(i, 1) Then
      If tmp = "" Then
        tmp = Cells(j, 1)
      Else
        tmp = tmp & "; " & Cells(j, 1)
      End If
    End If
 Next j
 Cells(i, 10) = tmp
Next i

Picture of Data

2 个答案:

答案 0 :(得分:0)

您尝试做的事情可以通过以下方式进行最低限度的描述:   - 尝试在字符串“1; 2; 3; 4; 11; 12; 13”中搜索“1”,仅返回“1”而不是“11”,“12”,“13”。< / em>的

这是一种方法:

  • 通过“;”
  • 将字符串拆分为数组
  • 在数组中搜索

代码如下所示:

Option Explicit

Public Sub TestMe()

    Dim inputA  As String
    Dim cnt     As Long
    Dim arr     As Variant

    inputA = "1;2;3;4;11;12;13"

    arr = Split(inputA, ";")

    For cnt = LBound(arr) To UBound(arr)
        If 1 = arr(cnt) Then
            Debug.Print "Found in position " & cnt
            Exit For
        End If
    Next cnt

End Sub

答案 1 :(得分:0)

您可以创建如下所示的UDF:

    Public Function FindID(rngToCheck As Range, strVal As String) As Boolean
        If InStr(1, ";" & Replace(rngToCheck.Value, " ", "") & ";", ";" & strVal & ";", vbTextCompare) > 0 Then FindID = True
    End Function

然后检查单元格如下,假设您的数据在单元格A2中:

     =FindID(A2,"1")