使用VBA比较两个工作簿

我试图比较两个不同的工作簿,一个名为“之后”(这是最新的),另一个名为“之前”,我想强调的差异,所以很容易确定两者之间的变化。

好,所以在我testing了一下后,我陷入了一个错误

“对象不支持这个属性或方法”。

下面是完整的代码,添加了评论,以便您可以按照我的思维过程:

Sub OpenCsv() Dim zcf, FolderPath, after, before, shtAfter, shtBefore As String Dim MotherWB As Workbook, MotherWS As Worksheet Dim wb As Workbook, ws, worksheetz As Worksheet Dim oneRange, aCell As Range Dim rng As Range Dim Answer As Integer Dim mycell As Range Dim mydiffs As Integer 'Sorts Things for MotherWB Set oneRange = Range("A4:Z9000") Set aCell = Range("F4") oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes 'Opens and sets both Workbooks with their respective sheets FolderPath = Application.ActiveWorkbook.Path after = FolderPath + "\" + "after.csv" before = FolderPath + "\" + "before.xlsm" Workbooks.Open (after) Set wb = Workbooks("after.csv") Set ws = wb.Worksheets("after") Set MotherWB = Workbooks("before.xlsm") Set MotherWS = MotherWB.Worksheets("before") 'Makes ws looks like MotherWS so we compare them With ws Columns("A:Z").AutoFit Selection.TextToColumns _ Destination:=Range("A1:A9000"), _ DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, _ ConsecutiveDelimiter:=False, _ Tab:=False, _ Semicolon:=False, _ Comma:=True, _ Space:=False, _ Other:=False Set oneRange = Range("A4:Z9000") Set aCell = Range("F4") oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes End With 'Questions if you want to compare both Answer = MsgBox("Uma vez aberto o relatório deseja comparar os dois?", vbYesNo + vbQuestion, "Comparar") If Answer = 6 Then 'For each cell in after that is not the same in before, color it yellow For Each mycell In wb.ws(after).UsedRange If Not mycell.Value = MotherWB.MotherWS(before).Cells(mycell.row, mycell.Column).Value Then mycell.Interior.Color = vbYellow mydiffs = mydiffs + 1 End If Next 'Display a message box to demonstrate the differences MsgBox mydiffs & " differences found", vbInformation ActiveWorkbook.Sheets(after).Select End If End Sub 

我从答案中返回6后得到了错误,说了我上面所说的。 我究竟做错了什么?

答案设置为布尔值,msgbox将返回一个整数。 声明一个整数,然后使用if语句将true / false放入您的答案variables中。 类似于下面的东西

 Dim temp as integer temp = MsgBox("Uma vez aberto o relatório deseja comparar os dois?", vbYesNo + vbQuestion, "Comparar") if temp = 6 then Answer = true else Answer = false endif