如何比较两个工作簿之间的唯一数据列

时间:2016-02-03 01:11:43

标签: excel-vba vba excel

我想将fortest1.xlsx中D列的数据与tests.xlsm中的F列进行比较。如果匹配,则什么也不做。如果它们不匹配,则将fortest.xlsx中的A列复制到C,并将test.xlsm中的C列复制到E.我可以知道如何实现这一目标吗?我的代码运行没有错误,但是,它没有产生任何结果。

先谢谢。

Sub test()

' Application.ScreenUpdating = True     Dim WbA As Workbook     设置WbA = thisworkbook

Dim WbB As Workbook
Set WbB = Workbooks.Open(Filename:="C:\Users\maggie\Desktop\fortest1.xlsx")

Dim SheetA As Worksheet
Dim SheetB As Worksheet
Set SheetA = WbA.Sheets("up")
Set SheetB = WbB.Sheets("up")

Dim eRowA As Integer
Dim eRowB As Integer
eRowA = SheetA.Range("F" & Rows.Count).End(xlUp).Row 'Last line with data in Workbook A (ActiveWorkbook)
eRowB = SheetB.Range("D" & Rows.Count).End(xlUp).Row  'Last line with data in Workbook B (Opened Workbook)

Dim match As Boolean
Dim erow As Long
Dim i, j As Long
Dim r1, r2 As Range
For i = 1 To eRowA
    Set r1 = SheetA.Range("F" & i)
    match = False
    For j = 1 To eRowB
        Set r2 = SheetB.Range("D" & j)
        If r1 = r2 Then
            match = True
        End If
        Next j
        If Not match Then
        erow = Range("C" & Rows.Count).End(xlUp).Row + 1
        SheetB.Range("A" & j & ":C" & j).Copy Destination:=SheetA.Range("C" & erow & ":E" & erow)
End If
Next i
WbB.Close (False)

End Sub enter image description here

1 个答案:

答案 0 :(得分:0)

我不太确定我理解你真正想要实现的目标,但代码有几个问题。

正确的缩进是其中一个问题。乍一看,代码是如何嵌套的并不明显。

  • 当比较不为真时,匹配变量不会重置为false,因此它仍显示为True。修复:将match = False移动到j循环中,因此在j循环开始时将其设置为False
  • 设置匹配变量,然后在j循环中重写七次,然后再进行评估。

以上建议应用于代码结果:

For i = 1 To eRowA
    Set r1 = SheetA.Range("F" & i)
'    match = False ' move this into the j loop
    For j = 1 To eRowB
        match = False
        Set r2 = SheetB.Range("D" & j)
        If r1 = r2 Then
            match = True
        End If
'        Next j   ' this loops too early and overwrites the match variable
        If Not match Then
            erow = Range("C" & Rows.Count).End(xlUp).Row + 1
            SheetB.Range("A" & j & ":C" & j).Copy Destination:=SheetA.Range("C" & erow & ":E" & erow)
        End If
    Next j
Next i

代码现在通过i循环运行两次,并且在每个i循环中运行七次循环。如果这不是你想要达到的目的,那就加油了。