簡體   English   中英

excel VBA工作表比較在Excel中使用VBA並將結果存儲在工作表中?

[英]excel vba sheet comparison using vba in excel and store result in a sheet?

我需要動態選擇兩個excel工作表的范圍,並逐行進行比較,並使用excel VBA宏將其打印在報表中,如true或false。請幫助。VBA宏比較兩個Excel文件的所有單元格該鏈接很有幫助,但我想動態選擇范圍,還需要在比較表中打印一些TRUE / FALSE。

我確實想將工作表加載到變量數組,然后遍歷它們以提高代碼的性能。

注意-請假設需要比較的兩個工作表都包含相同的行數並進行了排序。

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.
            ' i want to go to the exact cell in Comparison sheet and type TRUE Else
            ' Cells are different.
            ' i want to go to the exact cell in Comparison sheet and type FALSE
        End If
    Next iCol
Next iRow

這是一個樣本。 該示例代碼僅在比較選項卡中記錄不匹配的數組(i,j)坐標。 您應該對其進行修改以記錄所需的任何其他信息:

Sub CompareSheets()
    Dim s1 As Worksheet, s2 As Worksheet, s3 As Worksheet
    Dim rComp As Range, addy As String
    Dim I As Long, J As Long, K As Long
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    Set s3 = Sheets("comparison")
    s1.Select
    Set rComp = Application.InputBox(Prompt:="Select range", Type:=8)
    addy = rComp.Address
    ary1 = rComp
    ary2 = s2.Range(addy)
    K = 1
    For I = LBound(ary1, 1) To UBound(ary1, 1)
        For J = LBound(ary1, 2) To UBound(ary1, 2)
            If ary1(I, J) = ary2(I, J) Then
            Else
                s3.Cells(K, 1) = I
                s3.Cells(K, 2) = J
                K = K + 1
            End If
        Next J
    Next I
End Sub

編輯:

為了回應您的評論,此版本將在比較表中填充TRUE和FALSE:

Sub CompareSheets2()
    Dim s1 As Worksheet, s2 As Worksheet, s3 As Worksheet
    Dim rComp As Range, addy As String
    Dim I As Long, J As Long, K As Long
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    Set s3 = Sheets("comparison")
    s1.Select
    Set rComp = Application.InputBox(Prompt:="Select range", Type:=8)
    addy = rComp.Address
    ary1 = rComp
    ary2 = s2.Range(addy)
    ary3 = s3.Range(addy)
    K = 1
    For I = LBound(ary1, 1) To UBound(ary1, 1)
        For J = LBound(ary1, 2) To UBound(ary1, 2)
            If ary1(I, J) = ary2(I, J) Then
                ary3(I, J) = "TRUE"
            Else
                ary3(I, J) = "FALSE"
            End If
        Next J
    Next I
    s3.Range(addy) = ary3
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM