如何有条件地将一行Excel数据从一个工作表附加到另一个工作表?

时间:2012-03-29 17:02:17

标签: excel vba excel-vba excel-formula

我不经常使用Excel,但我希望有一种相当直接的方法来解决这个问题。我查看了一些其他解决方案,包括将数据从一个工作表粘贴到另一个工作表,但我找不到任何可以让我(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).

很抱歉,如果有更好的方式来形成这个问题。我已经设法让自己在圈子里思考,现在我觉得我的脸上有一种混乱的Nigel Tufnel样子。

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

2 个答案:

答案 0 :(得分:2)

我认为这是你要做的事情?

代码未经测试。我相信它应该有效。如果您有任何错误,请告诉我们,我们会在那里接受...

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

西特

答案 1 :(得分:0)

这应该有效:

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