其他分享
首页 > 其他分享> > VBA比较两个Excel数据的异同

VBA比较两个Excel数据的异同

作者:互联网

代码背景:

 

整体来说,需求非常明确,代码逻辑比较简单。

相关代码:

Sub CompareData()

    Dim i As Long
    Dim j As Long
    
    Dim fullSheetName As String
    fullSheetName = "Sheet1"
    Set fullSheet = Sheets(fullSheetName)
    Dim fullDataRange As Variant
    fullDataRange = fullSheet.Range("A1", "AN43921").CurrentRegion.Value
    Dim fullSheetRowMax As Long
    fullSheetRowMax = Range("A1", "AN43921").CurrentRegion.Rows.Count
    
    Dim partialSheetName As String
    partialSheetName = "Sheet2"
    Set partialSheet = Sheets(partialSheetName)
    Dim partialDataRange As Variant
    partialDataRange = partialSheet.Range("A1", "AN40000").CurrentRegion.Value
    Dim partialSheetRowMax As Long
    partialSheetRowMax = partialSheet.Range("A1", "AN40000").CurrentRegion.Rows.Count

    Dim columnMax As Integer
    columnMax = 40
    
    Dim columnMark As Integer
    columnMark = 42
    
    Dim sameRow As Boolean
    
    For i = 1 To fullSheetRowMax
        For j = 1 To partialSheetRowMax
            sameRow = True
            For columnIndex = 1 To columnMax
                If IsEmpty(fullDataRange(i, columnIndex)) And Not IsEmpty(partialDataRange(j, columnIndex)) Then
                    sameRow = False
                    Exit For
                End If
                If IsEmpty(partialDataRange(j, columnIndex)) And Not IsEmpty(fullDataRange(i, columnIndex)) Then
                    sameRow = False
                    Exit For
                End If
                If fullDataRange(i, columnIndex) <> partialDataRange(j, columnIndex) Then
                    sameRow = False
                    Exit For
                End If
            Next columnIndex
            
            If sameRow Then
                fullSheet.Cells(i, columnMark) = 1
                Exit For
            End If
        Next j
    Next i
    
    MsgBox "Successfully!"
End Sub

 

标签:Dim,VBA,End,columnIndex,异同,Excel,sameRow,partialDataRange,fullDataRange
来源: https://www.cnblogs.com/mingmingruyuedlut/p/12813041.html