我正在寻找能够执行以下操作的VBA代码:
这是一些可以澄清我正在寻找的伪代码:
对于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
此代码目前无效。
非常感谢您的帮助。
答案 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