查找范围中的一组单元格

时间:2013-10-16 16:05:26

标签: excel-vba foreach find vba excel

使用For EachFind方法,即使范围是多行多列,我也可以查找范围内的单元格。但是,如何在一个范围内寻找一组单元格呢?

例如,我有一个参考书,其行条目填充第2-7行,并且是两列宽。我需要找到它们是否与我的目标书中的行条目(也从第2行开始并且是两列宽)完全匹配。如果找到匹配项,则会将参考文件中的行#粘贴到第5列中。否则,它会粘贴到新条目中。这是迄今为止的代码:

Dim NewFile as Workbook  'defined as the location of the reference book  
Dim NewSht as Worksheet  'defined as the sheet in NewFile  
Dim ThisSht as Worksheet  'defined as the sheet in the target book
Dim NewName as Range  
Dim LastEntry as Range  
Dim OldNameRange as Range  
Dim EntryMatch as Range  
For Each NewName In NewSht.Range(NewSht.Cells(2, 1), NewSht.Cells(Rows.Count, 2).End(xlUp)) 'loops thru each set of entry labels in new sheet  
  Set LastEntry = ThisSht.Cells(Rows.Count, 2).End(xlUp)
  Set OldNameRange = ThisSht.Range(ThisSht.Cells(2, 1), LastEntry)
  Set EntryMatch = OldNameRange.Find(NewName.Value, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True)  
  If Not EntryMatch Is Nothing Then  
    ThisSht.Cells(EntryMatch.Row, 5).Value = NewName.Row  
  Else  
    ThisSht.Cells(LastEntry.Row + 1, 1).Resize(1, 2).Value = NewSht.Range(NewSht.Cells(NewName.Row, 1), NewName.Cells(NewName.Row, 2)).Value  
    ThisSht.Cells(LastEntry.Row + 1, 3).Value = NewName.Row  
  End If  
Next

现在,它只是逐个细胞地比较。任何人都可以帮助我将一组单元格(每行条目)与OldNameRange中的每组单元格进行比较吗?谢谢!

0 个答案:

没有答案