下面是一个简单的代码,用于检查 2 个工作簿之间的更改。1 是主工作簿,另一个是发送给我的更改列表。我确实都打开了,并且我确保它们在同一个实例中打开。代码存储在我的个人宏工作簿中,因此我可以检查多个文件。
我的代码在第一行就崩溃了。Set cSheet Workbooks("CNO_CostGroups_v2.xlsx").Worksheets("CostCenters")
没有错误,没有消息,什么都没有。Excel 只是进入无响应、崩溃并在自动恢复版本中重新打开所有内容。我已经使用键盘上的 F8 逐行浏览了这段代码。Excel 每次都崩溃,我无法通过这里。
这段代码在几周前编写时可以工作,之后又被使用了几次。我唯一的猜测是,也许我的 Excel 更新了,但没有真正的迹象表明它发生了。我不知道编写代码时它可能是什么版本,但现在我机器上的是 64 位,版本 2002,内部版本 12527.21416。I know I didn't change from 32 bit to 64 bit
.
我的问题是我能做什么?我什至尝试在即时窗口中运行此代码,它正确返回 A1 的值?Workbooks("CNO_CostGroups_v2.xlsx").Worksheets("CostCenters").Range("A1").Value
。是什么导致它崩溃?对我来说,这似乎很简单,并且您可以看到所有变量都已正确声明。
Sub CheckForChanges()
Dim nSheet As Worksheet, cSheet As Worksheet, cIndexRng As Range, nHeadRng As Range, nIndexRng As Range
Dim C As Range, col1 As Long, col2 As Long, row1 As Long, row2 As Long
'Must have master version of cost center groups open
'Set intitial values
Set cSheet = Workbooks("CNO_CostGroups_v2.xlsx").Worksheets("CostCenters")
Set cIndexRng = cSheet.Range("P1", cSheet.Range("P1").End(xlDown))
Set nSheet = ActiveSheet
Set nHeadRng = nSheet.Range("A1", nSheet.Range("A1").End(xlToRight))
Set nIndexRng = nSheet.Range("P2", nSheet.Range("P2").End(xlDown)) 'Ensure This part is referencing the correct index column (currently in column P)
col1 = 1
col2 = nHeadRng.Count
'Check the file structures are the same
For Each C In nSheet.Range("A1", nSheet.Range("A1").End(xlToRight))
If C.Value <> cSheet.Cells(1, col1).Value Then
MsgBox ("Make sure you have open a current Cost Center file and that the column headers match")
Exit Sub
End If
col1 = col1 + 1
Next C
'Begin checking file for changes. Needs updates in Yellow, new lines all together in Green
For Each C In nIndexRng
row1 = C.Row
If IsFound(C.Value, cIndexRng, row2) Then
If row1 = row2 Then nSheet.Cells(row1, 16).Interior.Color = RGB(146, 208, 80)
For col1 = 1 To col2
If nSheet.Cells(row1, col1).Value <> cSheet.Cells(row2, col1).Value Then
nSheet.Cells(row1, col1).Interior.Color = RGB(255, 255, 0)
End If
Next col1
Else
nSheet.Range(nSheet.Cells(row1, 1), nSheet.Cells(row1, col2)).Interior.Color = RGB(146, 208, 80)
End If
Next C
End Sub