就像我在我的評論中提到的那樣,您可以使用.Find
來實現您的目標。以下代碼示例打開工作簿A
和B
。然後循環遍歷工作簿A
中的列C的值,並嘗試在工作簿B
的列C中找到該值的出現次數。如果找到匹配,則比較該行中的所有列。如果所有列都匹配,則根據工作簿中的值A
寫入工作簿B
的列A和列B。一旦找到匹配項,它將使用.FindNext
作爲ColC的進一步匹配。
要測試此操作,請分別將您給我的文件保存爲C:\A.xls
和C:\B.xls
。現在打開一個新的工作簿並在模塊中粘貼這段代碼。該代碼與工作簿的Sheet7
比較工作簿A
的Sheet7
B
我相信你現在可以修改它的表
受審的其餘部分和測試(在後末見快照)
Sub Sample()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws1LRow As Long, ws2LRow As Long
Dim i As Long, j As Long
Dim ws1LCol As Long, ws2LCol As Long
Dim aCell As Range, bCell As Range
Dim SearchString As String
Dim ExitLoop As Boolean, matchFound As Boolean
'~~> Open File 1
Set wb1 = Workbooks.Open("C:\A.xls")
Set ws1 = wb1.Sheets("sheet7")
'~~> Get the last Row and Last Column
With ws1
ws1LRow = .Range("C" & .Rows.Count).End(xlUp).Row
ws1LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'~~> Open File 2
Set wb2 = Workbooks.Open("C:\B.xls")
Set ws2 = wb2.Sheets("sheet7")
'~~> Get the last Row and Last Column
With ws2
ws2LRow = .Range("C" & .Rows.Count).End(xlUp).Row
ws2LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'~~> Loop Through Cells of Col C in workbook A and try and find it
'~~> in Col C of workbook 2
For i = 2 To ws1LRow
SearchString = ws1.Range("C" & i).Value
Set aCell = ws2.Columns(3).Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
ExitLoop = False
'~~> If match found
If Not aCell Is Nothing Then
Set bCell = aCell
matchFound = True
'~~> Then compare all columns
For j = 4 To ws1LCol
If ws1.Cells(i, j).Value <> ws2.Cells(aCell.Row, j).Value Then
matchFound = False
Exit For
End If
Next
'~~> If all columns matched then wrtie to Col A/B
If matchFound = True Then
ws2.Cells(aCell.Row, 1).Value = ws1.Cells(i, 1).Value
ws2.Cells(aCell.Row, 2).Value = ws1.Cells(i, 2).Value
End If
'~~> Find Next Match
Do While ExitLoop = False
Set aCell = ws2.Columns(3).FindNext(After:=aCell)
'~~> If match found
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
matchFound = True
'~~> Then compare all columns
For j = 4 To ws1LCol
If ws1.Cells(i, j).Value <> ws2.Cells(aCell.Row, j).Value Then
matchFound = False
Exit For
End If
Next
'~~> If all columns matched then wrtie to Col A/B
If matchFound = True Then
ws2.Cells(aCell.Row, 1).Value = ws1.Cells(i, 1).Value
ws2.Cells(aCell.Row, 2).Value = ws1.Cells(i, 2).Value
End If
Else
ExitLoop = True
End If
Loop
End If
Next
End Sub
快照
前
後
'什麼是實現這一目標將是最好的方式任何有識之士根據您是appreciated.'什麼最好的辦法?你一定已經考慮過了:)你有沒有嘗試過任何代碼?向我們展示你所嘗試的代碼,並在此基礎上,我們可以告訴你,如果這是最好的方式,或者它可以改進;) – 2012-08-01 06:53:12
嗯,我想到的方式是最簡單的我能想到的。循環遍歷第一個工作簿的行,找到第二個工作簿中的每一個並替換它們。這就是說,我不知道如何比較範圍。 workbook1.sheet1.range(「C1:F1」)= orkbook2.sheet1.range(「C1:F1」)?然後替換整條線。我還沒有創建任何代碼,因爲我不確定這是否是最好的方法。有許多數據線,這可能是一種矯枉過正的方式。 – kokotas 2012-08-01 07:18:12
是循環將是一個矯枉過正。你可能想用'.FIND'看看這是否讓你開始。 http://siddharthrout.wordpress.com/2011/07/14/find-and-findnext-in-excel-vba/ – 2012-08-01 07:21:45