2013-06-12 153 views
1

我在單元格A1中有多個由';'分隔的值。一些相同的值可能在單元格B1中。我需要使用單元格B1中的值來搜索單元格A1中的值。所有未找到的值都需要在單元格C1中顯示。在單元格中搜索字符串

EG - 細胞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 
+1

你嘗試過什麼?發佈你的代碼並告訴我們什麼不起作用。閱讀「Split()」函數作爲起點 – 2013-06-12 09:51:13

+0

我無法在循環中工作。我嘗試這個代碼PLS赤子Splitvalue() 昏暗STR,myStr中作爲變 昏暗TP作爲整數 STR =分段(範圍( 「A1」)值, 「;」) 對於TP = LBOUND(STR )爲了UBound函數(STR) myStr的STR =(TP) 接着 結束子 – Mukul

回答

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

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 
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) 
相關問題