首页 文章

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

提问于
浏览
1

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

  • 在工作表1上,从A2开始,向下滚动并逐个比较每个单元格,第一列中的每个单元格,从B2开始 .

  • 如果匹配,请将第二列中匹配条目的整行复制到工作表2中

  • 如果在滚动列B后没有匹配项,则在工作表2中插入一个空行

这里有一些伪代码可以澄清我正在寻找的东西:

对于列A中的每个单元格
遍历columnB中的每个单元格
如果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 回答

  • 1

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

    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
    

相关问题