2013-05-21 202 views
1

我有兩個不同的工作表中的數據。 Sheet1.A將包含一個字母數字項「ABC123」和Sheet2.A將包含一個類似的項「ABC123一些文本」或「一些文本ABC123」比較匹配和非匹配的兩個數據集

此外Sheet1將總是有比Sheet2更少的條目,因此會有不匹配。

在工作表3中我希望能夠顯示Sheet1.A的所有條目以及來自Sheet2.A的相應匹配,然後對於所有不匹配,我希望它們顯示在列表的底部。理想輸出的

實施例:

Sheet3.A Sheet3.B 
ABC123 ABC123 
ABC222 ABC222 
ABC333 ABC333 
      ABC444 
      ABC555 
      ABC666 

目前我使用的折射率匹配(具有LEFT功能)公式Sheet3.B但不會產生理想的輸出:

Sheet3.A Sheet3.B 
ABC123 ABC123 
ABC222 ABC222 
ABC333 ABC333 
      ABC444 
      ABC444 
      ABC444 

另外因爲我正在使用LEFT函數並且Sheet2.A中的數據可能不會被安排爲類似於Sheet1.A,因此某些條目未找到,因此生成#N/A

我也想添加Sheet2.A可能包含超過256個字符導致索引匹配函數的問題。這個問題不是重中之重,但如果可以解決的話,那將會很好。

編輯:

問題和接受的答案現在可以正確地反映彼此

回答

1

你也許可以使用.Find方法,尋找部分匹配。

Sub FindPartialString() 

Dim wsList As Worksheet 
Dim wsSearch As Worksheet 
Dim wsOutput As Worksheet 
Dim lastRow As Long 
Dim rngList As Range 
Dim rngMatch As Range 
Dim cl As Range 
Dim arrNonMatches() As Variant 
Dim nonMatchCount As Long 


Set wsList = Sheets(1) '## Modify as needed 
Set wsSearch = Sheets(2) '## Modify as needed 
Set wsOutput = Sheets(3) '## Modify as needed 
Set rngList = wsList.Range("A2:A5") '## Modify as needed 

For Each cl In rngList 
    Set rngMatch = Nothing 'clear the container before each query 
    'look for a partial match: 
    Set rngMatch = wsSearch.Cells.Find(What:=cl.Value, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ 
     :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
     False, SearchFormat:=False) 

    'Store the matches and non matches in separate arrays: 
    If Not rngMatch Is Nothing Then 
     lastRow = 1 + Application.WorksheetFunction.CountA(wsOutput.Range("A:A")) 
     'put the searched value in column A: 
     wsOutput.Cells(lastRow, 1) = cl.Value 
     'Put the found value in column B: 
     wsOutput.Cells(lastRow, 2) = rngMatch.Value 
    Else: 
     'store non-matches in an array 
     ReDim Preserve arrNonMatches(nonMatchCount) 
     arrNonMatches(nonMatchCount) = cl.Value 
     nonMatchCount = nonMatchCount + 1 
    End If 
Next 

'Print out the non-matches 
lastRow = lastRow + 1 
wsOutput.Cells(lastRow, 1).Resize(UBound(arrNonMatches) + 1, 1).Value = Application.Transpose(arrNonMatches) 
End Sub 
+0

感謝大衛 - 您的解決方案非常接近達到我想要的輸出。不過,我應該澄清一些事情 - wsSearch中的項目可能不存在於wsSearch中。因此,當前子例程在wsOutput列A中輸出wsList非匹配項,在wsOutput列B中輸出空白。 – fresh

+0

這不正是你想要的嗎? 「那麼對於所有不匹配的情況,我希望它們顯示在列表的底部。」你想在B列中看到什麼?沒有匹配,所以我把非匹配放在列A的底部,因爲我理解了這個問題。 –

+0

我意外地提交了我的評論而沒有完整的回覆。我編輯了我的原始問題,以反映希望輸出中的這種變化 - 請原諒在原始問題中缺乏明確性。 – fresh

相關問題