我正在创建一个宏,用于检查工作簿中每个工作表的公式中的错误。该宏在触发BeforeSave挂钩时运行,并提示用户在发现错误时决定是否仍要保存。
Public Sub errorCheck()
On Error Resume Next
Application.StatusBar = "Running: formulaErrorCheck"
Dim ws As Worksheet
Dim errors As range
Dim r As range
For Each ws In Worksheets
Set errors = Nothing
Set errors = ws.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors).cells
If Not (errors Is Nothing) Then
For Each r In errors
If IsError(r.Value) = True Then
Select Case r.Value
Case CVErr(xlErrValue), CVErr(xlErrDiv0), CVErr(xlErrName), CVErr(xlErrRef)
If MsgBox("Excel Sheet " + ws.name + " contains a reference error in cell " + r.Address(False, False) + ". Save anyway?", vbYesNo, "") = vbNo Then
Application.GoTo Reference:=r
GoTo quit_checking
End If
End Select
End If
Next
End If
Next
quit_checking:
Application.StatusBar = False
End Sub
类模块中用于检测事件的代码:
OptionExplicit
Private WIthEvents App As Application
Private Sub App_WorkbookBeforeSave(ByVal wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
Book_BeforeSave SaveAsUI, Cancel
End Sub
Public Sub Book_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Call errorCheck
End Sub
我遇到的问题是
Set errors = ws.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors).cells
当我独立运行宏时,返回期望的单元格。但是,当从BeforeSave挂钩调用该宏时,它将返回整个使用范围。我认为对工作簿的引用可能是一个问题,但是工作表仍按预期进行迭代。我已尝试删除“错误恢复下一步”,以确保实际上没有引发任何错误。我不知道有什么区别。