是的,我知道還有一些與此相關的其他主題,但我認爲如果我創建另一個主題,會更好,因爲這有點不同。無論如何,如果有人認爲我沒有遵循論壇規則,請做你必須做的事。使用VBA比較兩個excel工作簿
我跟着這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用完內存或變得太慢?
媽呀,現在覺得很愚蠢笑 – dekio 2014-10-08 11:02:24
等待,我只是改變了這部分代碼,我仍然沒有得到不同的細胞。 – dekio 2014-10-08 11:04:21
@dekio:好的我更新了我的答案 – marg 2014-10-08 11:13:34