使用VBA比较两个Excel工作簿

是的,我知道还有其他一些与此有关的话题,但是我认为如果我创build另一个话题会更好,因为这有点不同。 无论如何,如果有人认为我没有遵循论坛规则,请做你必须做的事情。

我正在关注这个正在谈论比较两个工作簿的文章。 由于我想比较两个具有相同内容的Excel文件,我做了一个非常相似的代码。 但是,我的代码似乎没有比较这两个文件,而是比较文件A与文件A或文件B与文件B.

代码的作用是获取两个工作簿,获取名为“资产负债表”的工作表,然后比较两个工作簿中的资产负债表是否具有相同的值。 所以我们不必遍历所有的单元格,表单被加载到一个Variant数组中。 你可以看到一个资产负债表的图片只是为了有一个想法: http : //i.stack.imgur.com/tc8Nr.png

我的代码是这样的:

Sub CompareWorkbooks() 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(Filename:="C:\Users\Desktop\BalanceSheet.xls") Set varSheetA = wbkA.Worksheets("Balance sheet") ' or whatever sheet you need Set wbkB = Workbooks.Open(Filename:="C:\Users\Desktop\BalanceSheet_old.xls") Set varSheetB = wbkB.Worksheets("Balance sheet") ' or whatever sheet you need strRangeToCheck = "B6:D49" ' If you know the data will only be in a smaller range, reduce the size of the ranges above. Debug.Print Now varSheetA = Worksheets("Balance Sheet").Range(strRangeToCheck) varSheetB = Worksheets("Balance Sheet").Range(strRangeToCheck) ' or whatever your other sheet is. Debug.Print Now 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 ' Cells are different. Let's fill our main template with the information Windows(MainTemplate.xlsm).Activate Cells(nlin, ncol) = varSheetA(iRow, 2) 'Gives the name of the changed field Cells(nlin, ncol + 1) = varSheetA(iRow, iCol) 'Gives me the value in workbookA Cells(nlin, ncol + 2) = varSheetB(iRow, iCol) 'Gives me the value in workbookB Cells(nlin, ncol + 3) = nlin 'Gives me the row location Cells(nlin, ncol + 4) = ncol 'Gives me the column location nlin = nlin + 1 End If Next Next End Sub 

任何人都可以猜测错误在哪里? 为什么我没有得到不同的细胞?

另外,我发现了一个新的问题,是不是可以让所有的表格都显示出来? 在我的代码中,我必须插入“资产负债表”作为工作表名称,但如果我有几个工作表? 即使通过循环,有没有人有一个好主意,这不会让我的excel用完内存或得到太慢?

您正在使用工作簿A设置sheetB。

 Set varSheetB = wbkA.Worksheets("Balance sheet") ' or whatever sheet you need 

应该:

 Set varSheetB = wbkB.Worksheets("Balance sheet") ' or whatever sheet you need 

对不起,我第一次错过了这个:

 varSheetA = Worksheets("Balance Sheet").Range(strRangeToCheck) varSheetB = Worksheets("Balance Sheet").Range(strRangeToCheck) 

应该:

 varSheetA = varSheetA.Range(strRangeToCheck) varSheetB = varSheetB.Range(strRangeToCheck) 

直接调用工作表函数将始终引用ActiveWorkbook。 而是始终从相关对象(wkbA.Worksheets(“…”)或wkbB.Worksheets(“…”))中调用它

顺便说一句。 你也可以将两个任务合并为一个:

 strRangeToCheck = "B6:D49" Set wbkA = Workbooks.Open(Filename:="C:\Users\Desktop\BalanceSheet.xls") Set varSheetA = wbkA.Worksheets("Balance sheet").Range(strRangeToCheck) Set wbkB = Workbooks.Open(Filename:="C:\Users\Desktop\BalanceSheet_old.xls") Set varSheetB = wbkB.Worksheets("Balance sheet").Range(strRangeToCheck)