Excel宏-比较Excel文件

时间:2018-06-25 12:48:48

标签: excel vba excel-vba

要比较两个Excel文件,下面是代码,我遇到以下错误:

  

“类型不匹配错误”。

请您帮忙

Sub Compare_Two_Excel_Files()
    Dim Ab As Integer, AbName As Integer
    Dim F1_Workbook As Workbook, F2_Workbook As Workbook
    Dim iRow As Double, iCol As Double, iRow_Max As Double, iCol_Max As Double
    Dim File1_Path As String, File2_Path As String, F1_Data As String, F2_Data As String

    File1_Path = ThisWorkbook.Sheets(1).Cells(1, 2)
    File2_Path = ThisWorkbook.Sheets(1).Cells(2, 2)
    iRow_Max = ThisWorkbook.Sheets(1).Cells(3, 2)
    iCol_Max = ThisWorkbook.Sheets(1).Cells(4, 2)

    Set F2_Workbook = Workbooks.Open(File2_Path)
    Set F1_Workbook = Workbooks.Open(File1_Path)
    ThisWorkbook.Sheets(1).Cells(6, 2) = F1_Workbook.Sheets.Count

    For Ab = 1 To F1_Workbook.Sheets.Count
        AbName = F1_Workbook.Sheets(Ab).Name
        ThisWorkbook.Sheets(1).Cells(7 + Ab, 1) = AbName
        ThisWorkbook.Sheets(1).Cells(7 + Ab, 2) = "Identical Sheets"
        ThisWorkbook.Sheets(1).Cells(7 + Ab, 2).Interior.Color = vbGreen

        For iRow = 1 To iRow_Max
            For iCol = 1 To iCol_Max
                F1_Data = F1_Workbook.Sheets(AbName).Cells(iRow, iCol)
                F2_Data = F2_Workbook.Sheets(AbName).Cells(iRow, iCol)

                If F1_Data <> F2_Data Then
                    F1_Workbook.Sheets(AbName).Cells(iRow, iCol).Interior.Color = vbYellow
                    ThisWorkbook.Sheets(1).Cells(7 + Ab, 2) = "Mismatch Found"
                    ThisWorkbook.Sheets(1).Cells(7 + Ab, 2).Interior.Color = vbYellow
                End If
            Next iCol
        Next iRow
    Next Ab
    ThisWorkbook.Sheets(1).Activate
    MsgBox "Task Completed"
End Sub

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您已经声明了AbName As Integer,并且应该将其声明为String:

AbName As String