Loops 比较两个工作表,找到第一个匹配项并粘贴,然后删除源行
我有两个工作表,当在活动工作表中找到第一个匹配项时,我想从第二个工作表(Sheet1)粘贴两个单元格。然后删除Sheet1中的源行。我无法从活动工作表的最后一行循环,因为我要从匹配的顶部填充第一行。我还在努力激活Sheet1以删除该行:Loops 比较两个工作表,找到第一个匹配项并粘贴,然后删除源行,loops,excel,delete-row,vba,Loops,Excel,Delete Row,Vba,我有两个工作表,当在活动工作表中找到第一个匹配项时,我想从第二个工作表(Sheet1)粘贴两个单元格。然后删除Sheet1中的源行。我无法从活动工作表的最后一行循环,因为我要从匹配的顶部填充第一行。我还在努力激活Sheet1以删除该行: Sub moveRecords() Dim i, j As Long With ActiveSheet 'need to work down in active sheet in order to populate the first match wit
Sub moveRecords()
Dim i, j As Long
With ActiveSheet
'need to work down in active sheet in order to populate the first match with cells 1 & 2
For i = 2 To 100
For j = 2 To 1000
If Cells(n, 1).Value = Sheets("Sheet1").Cells(j, 1).Value _
And Cells(n, 2).Value = Sheets("Sheet1").Cells(j, 2).Value Then
Cells(n, 7).Value = Sheets("Sheet1").Cells(j, 1).Value
Cells(n, 8).Value = Sheets("Sheet1").Cells(j, 2).Value
'need to delete the source row in Sheet1
End If
Next j
Next n
End With
End Sub
这里有一个稍微不同的方法,因为您想要删除整行,所以很难保持i或j变量的正确轨迹,所以这段代码将所有的复制和粘贴标记您必须删除的行,然后将它们全部删除,我对您的要求有点困惑,但我想就是这样了=]
Sub moveRecords()
For j = 2 To 100
If Sheets("Sheet1").Cells(j, 1).Value = Sheets("Sheet2").Cells(j, 1).Value _
And Sheets("Sheet1").Cells(j, 2).Value = Sheets("Sheet2").Cells(j, 2).Value Then
Sheets("Sheet1").Cells(j, 7).Value = Sheets("Sheet2").Cells(j, 1).Value
Sheets("Sheet1").Cells(j, 8).Value = Sheets("Sheet2").Cells(j, 2).Value
Worksheets("Sheet2").Cells(j, 1) = "Delete"
End If
Next
For i = 2 To 100
If Worksheets("Sheet2").Cells(i, 1) = "Delete" Then
Worksheets("Sheet2").Cells(i, 1).EntireRow.Delete
i = i - 1
End If
Next
End Sub
如果表1和表2上的数据如下所示: 以下是解决方案:
Sub test()
Set ExcelApp = CreateObject("Excel.Application")
Set wb = ActiveWorkbook
Set ws = wb.Worksheets("Sheet1")
Set ws1 = wb.Worksheets("Sheet2")
Set Rng = ws.UsedRange
RowCount = Rng.Rows.Count
Set Rng1 = ws1.UsedRange
RowCount1 = Rng.Rows.Count
For n = 1 To RowCount
For j = 1 To RowCount1
If ws.Cells(n, 1).Value = ws1.Cells(j, 1).Value _
And ws.Cells(n, 2).Value = ws1.Cells(j, 2).Value Then
ws.Cells(n, 7).Value = ws1.Cells(j, 1).Value
ws.Cells(n, 8).Value = ws1.Cells(j, 2).Value
ws1.Cells(j, 1).EntireRow.Delete
'To set the search to start from top row
j = 0
End If
Next j
Next n
End Sub
输出将是:
您能澄清一下您的要求吗?您试图查找的源数据在哪里?如果您能提供您的需求的图形表示,那就更好了。下面是最终结果的图片,它从表2中的数据中得到了表1中填充的第7列和第8列,其中有匹配项。然后需要删除sheet2中的源行。我第一次来这里,所以需要弄清楚如何粘贴图片。很快回来似乎添加的图片与Chrome的效果不太好,所以我使用了IE。结果发现,在我获得“10”的声誉之前,我无法发布图片。哦,我尝试过:(编辑代码将sheet1更新为sheet2。sheet1是活动的工作表,我想从sheet2中提取数据,其中两个字段匹配子If单元格(n,1)。Value=Sheets(“sheet2”)。Cells(j,1)。Value和Cells(n,2)。Value=Sheets(“sheet2”)。Cells(j,2)。Value然后是Cells(n,7)。Value=Sheets(“Sheet2”).Cells(j,1).Value Cells(n,8).Value=Sheet2”).Cells(j,2).Value'需要删除Sheet2中的源行,请您解释一下
i
和n
应该是什么?在我看来,您从未初始化或更改n
,而且i
从未使用过。