Excel将两个列从一个工作表复制整个匹配的行复制到新工作表

时间:2014-04-12 01:34:01

标签: excel excel-vba vba

我正在寻找能够执行以下操作的VBA代码:

  • 在工作表1上,从A2开始,向下滚动并逐个比较每个单元格,第二列中的每个单元格,从B2开始。
  • 如果匹配,请将第二列中匹配条目的整行复制到工作表2
  • 如果在滚动列B后没有匹配项,请在工作表2中插入空白行

这是一些可以澄清我正在寻找的伪代码:

对于A列中的每个单元格 遍历B列中的每个单元格 如果columnA中的当前单元格值与columnB中的当前单元格值匹配 复制当前columnB位置的整行 如果我们遍历了整个columnB并且没有找到匹配的话 在sheet2中插入一个空行

这是我能想到的最好的,但我并不精通操作excel表:

Sub rowContent()

Dim isMatch As Boolean
isMatch = False

Dim newSheetPos As Integer
newSheetPos = 1

Dim numRows As Integer
numRows = 591

Dim rowPos As Integer
rowPos = 1

For i = 1 To numRows 'Traverse columnA 
 For j = 1 To numRows 'Traverse columnB
    'Compare contents of cell in columnA to cell in ColumnB
    If Worksheets("Sheet1").Cells(i, 1) = Worksheets("Sheet1").Cells(j, 2) Then
        Worksheets("Sheet1").Cells(i, 1).Copy Worksheets("Sheet2").Cells(newSheetPos, 1)
        newSheetPos = newSheetPos + 1'prepare to copy into next row in Sheet2
        isMatch = True 
    End If

    j = j + 1 'increment j to continue traversing columnB
 Next
 'If we have traverse columnB without finding a match
 If Not (isMatch) Then 
        newSheetPos = newSheetPos + 1 'skip row in Sheet2 if no match was found
 End If
 isMatch = False
Next
End Sub

此代码目前无效。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我已对您的代码进行了更改。这应该作为你的伪代码描述:

Sub rowContent()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim i As Long, j As Long
    Dim isMatch As Boolean
    Dim newSheetPos As Integer

    Set ws1 = ActiveWorkbook.Sheets("Sheet1")
    Set ws2 = ActiveWorkbook.Sheets("Sheet2")

    'Initial position of first element in sheet2
    newSheetPos = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row

    For i = 1 To ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row
        isMatch = False
        For j = 1 To ws1.Cells(ws1.Rows.Count, 2).End(xlUp).Row
            If ws1.Cells(i, 1).Value = ws1.Cells(j, 2).Value Then
                ws1.Cells(j, 2).EntireRow.Copy ws2.Cells(newSheetPos, 1)
                isMatch = True
                newSheetPos = newSheetPos + 1
            End If
        Next j
        If isMatch = False Then newSheetPos = newSheetPos + 1
    Next i
End Sub