如何防止使用UDF在工作簿中重命名工作表时Excel崩溃

我有一个包含两个UDF的工作表。 他们的内容(除了一行之外)对于手头的问题并不是那么有趣,但是对于好奇,他们是:

Function finn_prioritert_oppgave(nummer As Long) As String Dim i As Long, r As Range, c As Range Set r = Range(PDCA.Range("N11"), PDCA.Range("N1048576").End(xlUp)) If Not Intersect(r, PDCA.Range("N10")) Is Nothing Then Set r = PDCA.Range("N11") End If For Each c In r If Not IsEmpty(c) Then nummer = nummer - 1 End If If nummer = 0 Then Exit For End If Next If nummer > 0 Then finn_prioritert_oppgave = CVErr(xlErrNA) Else finn_prioritert_oppgave = c.Offset(0, -11).Value End If End Function Function finn_status_oppgave(oppgave As Range) As String Application.Volatile Dim r As Range, i As Long, satisfied As Boolean Call deaktiver Set r = Range(PDCA.Range("C11"), PDCA.Range("C1048576").End(xlUp)) Set r = r.Find(what:=oppgave, LookIn:=xlValues, lookat:=xlWhole) finn_status_oppgave = "" If Not r Is Nothing Then Set r = PDCA.Range("J" & CStr(r.Row) & ":M" & CStr(r.Row)) i = 4 satisfied = False Do If Not IsEmpty(r.Cells(1, i)) Then Debug.Print PDCA.Range("J9:M9").Cells(1, i) finn_status_oppgave = PDCA.Range("J9:M9").Cells(1, i) satisfied = True End If i = i - 1 Loop While i >= 1 And Not satisfied End If Call reaktiver End Function 

问题是,据我所知,与第二个function,因为它包含行Application.Volatile 。 我一整个早上都苦于与工作簿,没有运气,以确定为什么Excel崩溃,当我尝试重新命名其中的工作表。 最后试图谷歌遍历我的代码,寻找错误后,我碰到了这个线程在Excel论坛,声称由于上述function发生问题。

显然地

如果您有一个易失性函数(您的代码函数包含“Application.Volatile(True)”标签),更改DisplayAlerts状态的位置(例如“Application.DisplayAlerts = False”),那么如果更改了名称包含这两个命令的函数的工作簿中的Excel工作表(至2010年,尚未在2013年进行testing)将崩溃

我没有在我的代码中使用Application.DisplayAlerts = False ,但是症状非常相似,以至于我确信它是导致问题的易失性函数:

错误信息

有什么我可以做,以防止这种错误发生,或者我应该只是使其非易失性,并使计算发生在Workbook_SheetChange -Event上的例如Application.CalculateFull

你的deaktiver和reaktiver几乎肯定下,因为你没有parsing他们。 没有太多没有参数的函数!

如果任何一个deaktiver或reaktiver尝试更改任何应用程序,工作簿,工作表或范围属性,那么调用函数将失败! 这将包括诸如设置Application.DisplayAlerts = False类的事情。

工作表中的函数只能更改它们所在的单元格的值。 他们只能返回函数结果。

你使用函数来计算 – 你需要改变的东西。

Subs可以调用函数,但函数不应该调用subs。