【发布时间】:2014-10-08 10:28:58
【问题描述】:
是的,我知道还有一些与此相关的其他主题,但我认为如果我创建另一个主题会更好,因为这有点不同。无论如何,如果有人认为我没有遵守论坛规则,请做你必须做的。
我正在关注这个post,它正在讨论比较两个工作簿。因为我想比较两个具有相同内容的 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 内存不足或变得太慢?
【问题讨论】: