Excel切换至自动计算时,是否重算非活动工作表的Dirty单元格?
问题:Excel 365中标记Dirty的跨工作表UDF单元格仅活动工作表重算
问题背景
在Excel 365(2308版本)中运行一款XLAM加载项,核心功能为:
- 遍历
ActiveWorkbook查找包含特定UDF的单元格,将其标记为Dirty - 全程通过程序将
Calculation设置为手动模式,完成UDF引用数据的更新后,切换回自动计算模式
预期切换至自动计算时,所有工作表中标记为Dirty的单元格都会重算,但在包含多个较大工作表的场景中,仅活动工作表会触发重算,其他工作表无任何变化。
可通过加载项退出时强制重算整个工作簿解决,但部分工作表计算量极大、耗时久,若Dirty单元格值未变更则无此必要,希望仅重算必要单元格(仅当输入变更时才需全工作簿重算)。
更新1
ChatGPT称Range.Dirty的标记仅能存在于单个工作表,切换工作表时之前的标记会被清除,但这无法解释当前场景——切换至自动计算时始终只有活动工作表正确重算,其他工作表需手动触发或强制全量重算才会更新。
更新2 - 补充代码
以下是精简后的核心代码,已确认无低级错误:
Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets ' Loop through each worksheet (ignore charts etc.) formatable = can_edit_format(ws) ' Search for all cells on the sheet that contain the relevant formula Application.StatusBar = "Scanning sheet: '" & ws.Name & "' for refStrings." Set GSDcells = Nothing cell_values = ws.UsedRange.Value2: cell_formulae = ws.UsedRange.formula: rcount = UBound(cell_values, 1): ccount = UBound(cell_values, 2) For rnum = 1 To rcount For cnum = 1 To ccount If Left(cell_formulae(rnum, cnum), 1) <> "=" Then ElseIf InStr(1, LCase(cell_formulae(rnum, cnum)), LCase(func_name)) > 0 Then cell_formula = cell_formulae(rnum, cnum) If IsError(cell_values(rnum, cnum)) Then ' Catch the #N/A cases that cause the line below to fail ElseIf is_valid_func(cell_formula) Then append_to_range GSDcells, ws.cells(rnum, cnum) Else ' If cell formula is not valid, mark it in a way that is no relevant End If End If SkipCell: Next cnum Next rnum If Not GSDcells Is Nothing Then GSDcells.Dirty If formatable Then GSDcells.Font.Color = GSD_Font_Colour ' Format all found cells GREEN End If SkipSht: Next ws ... Public Sub append_to_range(range_to_extend As Range, cell_item As Range) ' Appends cell_item to range_to_extend If range_to_extend Is Nothing Then Set range_to_extend = cell_item Else Set range_to_extend = Union(range_to_extend, cell_item) End If End Sub
说明:SkipCell和SkipSht是错误处理的恢复点,不影响核心逻辑;采用数组遍历的方式是为避免大UsedRange导致Excel崩溃,稳定性更强。
内容的提问来源于stack exchange,提问作者RobBaker
相关产品推荐
相关产品推荐

