如何有条件地将一行Excel数据从一个表单追加到另一个表单中?

我不经常使用Excel,但我希望有一个相当简单的方法来解决这个问题。 我研究了一些其他解决scheme,包括将数据从一个表格粘贴到另一个表格,但是我找不到任何可以让我(1)将单元格从一个表格匹配到另一个表格,然后(2)有条件地附加或连接数据而不是简单地粘贴它。

我有两张数据的Excel文档。 这两张表都包含一个数字ID列。 我基本上需要将Sheet2中的ID与Sheet1匹配,然后将Sheet2中的行数据附加到Sheet1中匹配的行上。 我会想象它会看起来像这样:

If Sheet2 ColumnA Row1 == Sheet1 ColumnA RowX Copy Sheet2 Row1 Columns Paste (Append) to Sheet1 RowX (without overwriting the existing columns). 

对不起,如果有更好的方式来形成这个问题。 我已经设法认为自己在圈子里,现在我觉得我有一个困惑的奈杰尔Tufnel看在我的脸上。

[更新:更新以澄清要复制的单元格。]

我想这就是你想要做的?

代码未经testing。 我相信它应该工作。 如果你有任何的错误,让我知道,我们会在那里形成…

 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

希德

这应该工作:

 For Each cell2 In Sheet2.UsedRange.Columns(1).Cells For Each cell1 In Sheet1.UsedRange.Columns(1).Cells If cell2.Value = cell1.Value Then Sheet1.Range("B" & cell1.Row & ":Z" & cell1.Row).Value = Sheet2.Range("B" & cell2.Row & ":Z" & cell2.Row).Value End If Next cell1 Next cell2