在单元格中搜索字符串

时间:2013-06-12 09:44:58

标签: vba excel-vba excel

我在单元格A1中有多个值,这些值由&#39 ;;'分隔。一些相同的值可能在单元格B1中。我需要使用单元格B1中的值搜索单元格A1中的值。然后,所有未找到的值都需要在单元格C1中显示。

例如 - 细胞A1(苹果;橙子;樱桃)细胞B1(苹果;橙子;)细胞c1需要反映"樱桃"没找到

我试过这段代码:

Sub Splitvalue() 
    Dim str, mystr As Variant 
    Dim tp As Integer 
    str = Split(Range("A1").Value, ";") 
    For tp = LBound(str) To UBound(str) 
        mystr = str(tp) 
    Next 
End Sub

3 个答案:

答案 0 :(得分:0)

为什么不像拆分第一个细胞一样拆分第二个细胞?然后看看你是否在B1中找到A1的每个元素,否则输出到C1?

这不优雅,但可行:

Sub Splitvalue()
    Dim str, mystr As Variant
    Dim stri As Variant
    Dim tp As Integer
    str = Split(Range("A1").Value, ";")
    str2 = Split(Range("B1").Value, ";")
    For tp = LBound(str) To UBound(str)
        mystr = str(tp)
        'Debug.Print mystr
        Dim found As Boolean
        found = False
        For Each stri In str2
            'Debug.Print stri
            If stri = mystr Then
                found = True
            End If
        Next stri
        If found = False Then
            Debug.Print mystr
        End If
    Next
End Sub

答案 1 :(得分:0)

像这样设置sheet1

setup sheet1

使用此代码

Option Explicit

Sub Splitvalue()

   Dim lastRow As Long
   lastRow = Range("A" & Rows.Count).End(xlUp).Row

   Dim c As Range
   Dim A As Variant, B As Variant
   Dim i As Long, j As Long
   Dim x As Boolean

   Columns(3).ClearContents

   For Each c In Range("A1:A" & lastRow)
      A = Split(c, ";")
      B = Split(c.Offset(0, 1), ";")
      For i = LBound(A) To UBound(A)
         For j = LBound(B) To UBound(B)
            If A(i) = B(j) Then
               x = True
               Exit For
            Else
               x = False
            End If
         Next j
         If Not x Then
            If IsEmpty(c.Offset(0, 2)) Then
               c.Offset(0, 2) = A(i)
            Else
               c.Offset(0, 2).Value = c.Offset(0, 2).Value & ";" & A(i)
            End If
         End If
      Next i
   Next

End Sub

,您的结果应如下所示 result

答案 2 :(得分:0)

一种方式:

dim needle() as string: needle = split(Range("B1").Value, ";")
dim haystack as string: haystack = ";" & Range("A1").Value & ";"
dim i as long

for i = 0 To ubound(needle)
    haystack = replace$(haystack, ";" & needle(i) & ";", ";")
next

If len(haystack) = 1 then haystack = ";;"
Range("C1").Value = Mid$(haystack, 2, Len(haystack) - 2)