我觉得这是什么你想干什么?
该代码未经测试。我相信它应该起作用。如果你得到任何错误,让我知道,我们将会把它在那里形成...
Sub Sample()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws1LR As Long, ws2LR As Long
Dim i As Long, j As Long, LastCol As Long
Dim ws1Rng As Range, aCell As Range
Dim SearchString
Set ws1 = Sheets("Sheet1")
'~~> Assuming that ID is in Col A
'~~> Get last row in Col A in Sheet1
ws1LR = ws1.Range("A" & Rows.Count).End(xlUp).Row
'~~> Set the Search Range
Set ws1Rng = ws1.Range("A1:A" & ws1LR)
Set ws2 = Sheets("Sheet2")
'~~> Get last row in Col A in Sheet2
ws2LR = ws2.Range("A" & Rows.Count).End(xlUp).Row
'~~> Loop through the range in Sheet 2 to match it with the range in Sheet1
For i = 1 To ws2LR
SearchString = ws2.Range("A" & i).Value
'~~> Search for the ID
Set aCell = ws1Rng.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> If found
If Not aCell Is Nothing Then
LastCol = ws2.Cells(i, ws2.Columns.Count).End(xlToLeft).Column
'~~> Append values
For j = 2 To LastCol
ws1.Cells(aCell.Row, j).Value = ws1.Cells(aCell.Row, j).Value & " " & ws2.Cells(i, j).Value
Next j
End If
Next i
End Sub
HTH
希德
如果行X中找到匹配的,那么你想将其添加到行Z?即在(n + 2)的位置,其中n与X相同。我的理解是否正确? – 2012-03-29 17:34:48
抱歉,文字混乱。通过“Sheet1 ColumnA RowX”我只是指任何与“Sheet2 ColumnA Row1”中的数据相匹配的行。 – Bijan 2012-03-29 18:36:47
当你说追加时,你是说如果单元格有“SAMPLE1”,那么它应该追加到它,所以它看起来像“SAMPLE1 SAMPLE2”? – 2012-03-29 19:02:38