2013-05-21 204 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

相关问题