我希望从两个单独的工作簿(WB1和WB2)中过滤数据得到一些帮助。我想比较两个工作簿之间两列的数据,如果数据匹配,那么我将两个列项复制到新工作簿(WB3)。
因此,只有当col1和col2在WB1和WB2之间匹配时,才能在WB3上复制项目。
答案 0 :(得分:0)
为了鼓励您自己尝试解决问题,我将仅限于展示您应该能够适应您需求的示例代码。该方法在性能方面可能并不完美,但只要你想匹配唯一的,而不是重复的值,它就是100%可靠的(我希望)。
您需要创建一个For循环,其中变量保存WB1中的值,并嵌套另一个For循环,将该变量与WB2中的单元格进行比较。
Sub CopyBetweenWorksheets()
Application.ScreenUpdating = False
Dim i As Long, k As Long, ws1 As Worksheet, ws2 As Worksheet, myVar As Double
Set ws1 = Workbooks("First workbook").Worksheets("Sheet 1")
Set ws1 = Workbooks("Second workbook").Worksheets("Sheet 1")
'obviously just examples
For i = 2 To 150 'example last row of ws1
myVar = ws1.Cells(i, 1)
For k = 2 To 320 'example last row of ws2
If ws2.Cells(k, 1) = myVar Then
'your commands what to copy go here
Exit For 'this is an important line that speeds it up a lot
End If
Next k
Next i
End Sub