我有一个Excel电子表格,其中有2个工作表。在A列的第一个工作表中,我有一个商店名称。第二个工作表是工作表1的子集,也有商店名称,但它们位于工作表2的B列中。我需要将工作表1中的每个商店名称(列A)与工作表中的每个商店名称(列B)进行比较2并提取2相交的位置(具有相同的商店名称)。到目前为止,我已经在VB中完成了以下操作:
Sub RunMe()
Dim lRow, x As Long
Sheets("Sheet1").Select
lRow = Range("A2").End(xlDown).Row
For Each cell In Range("B2:B" & lRow)
x = 2
Do
If cell.Value = Sheets("Sheet1").Cells(x, "A").Value Then
cell.EntireRow.Copy Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
End If
x = x + 1
Loop Until IsEmpty(Sheets("Sheet1").Cells(x, "A"))
Next
End Sub
如何修改上面的代码,将工作表1的每个商店名称(A列)与工作表2的每个商店名称(B列)进行比较?
答案 0 :(得分:1)
试试这个
Sub RunMe()
Dim cell1 As Range, cell2 As Range
Dim rng1 As Range, rng2 As Range
Set rng1 = GetRange("Sheet1",1)
Set rng2 = GetRange("Sheet2",2)
For Each cell2 In rng2
For Each cell1 In rng1
If cell1.Value = cell2.Value Then
cell2.EntireRow.Copy Worksheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
End If
Next
Next
End Sub
Function GetRange(shtName As String, colIndex as Long) As Range
With Worksheets(shtName)
Set GetRange = .Range(.Cells(2, colIndex), .Cells(.Rows.Count, colIndex).End(xlUp))
End With
End Function