VBA宏,用于比较一行并查看它是否存在于另一个工作簿中

时间:2017-06-23 19:21:03

标签: excel vba excel-vba

我试图创建一个VBA代码,如果另一个工作簿中存在一行,则会逐行检查,并反复执行,直到它用完行以检入另一个工作簿。然后,对于每行,它发现不存在将其副本发送到新工作簿。我已经尝试了几周搜索,但每个人都想检查是否存在单行,我需要检查另一个工作簿中是否存在500k行。

Private Sub CommandButton3_Click()

Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long


nlin = 1
ncol = 1

'Get the worksheets from the workbooks
Set wbkA = Workbooks.Open(Application.GetOpenFilename)
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

Set wbkB = Workbooks.Open(Application.GetOpenFilename)
Set varSheetB = wbkB.Worksheets("Sheet1") ' or whatever sheet you need

strRangeToCheck = "A1:A999999"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = varSheetA.Range(strRangeToCheck)
varSheetB = varSheetB.Range(strRangeToCheck)
Debug.Print Now


Dim ws As Variant

'Set lol = Workbooks.Open("LOL.xlsm")
Set ws = Workbooks.Add.Sheets("Sheet1")

For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
    For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
        If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
            ' Cells are identical.
            ' Do nothing.
        Else

            ws.Cells(nlin, ncol + 1) = varSheetA(iRow, iCol) 'Gives me the value in workbookA
            ws.Cells(nlin, ncol + 2) = varSheetB(iRow, iCol) 'Gives me the value in workbookB

            nlin = nlin + 1

        End If
    Next
Next
ws.Cells.EntireColumn.AutoFit
End Sub

这就是我所拥有的,但它只检查同一行之间的差异,这不是我想要的。

1 个答案:

答案 0 :(得分:0)

这不是一个" cody"做事的方式,更像是使用辅助列操作Excel电子表格,但是如果将screenupdating设置为false,则比循环遍历行和列并检查每行和单元格对第二张的布尔操作要快得多。这只是两个工作表做1000行的一个例子,我省略了声明,实际上只是为了突出显示技术而复制:

var1 = elem1.attribute
var2 = elem2.attribute
if (var1 && var2 && var1 != var2) {
    report conflict
} else if (!var1 || !var2) { // one is null
    value = var1 || var2; // Get the non-null value
    var1.attribute = var2.attribute = value // Assign it to both
}