Application.Volatile崩溃在关闭

时间:2015-06-15 22:51:51

标签: excel-vba vba excel

我有一个标记为volatile的函数。此函数在公式中调用,并在每次更新公式中的单元格时执行。

我注意到在Workbook_BeforeClose()事件之后excel崩溃了。 Upcon评论函数excel中的Applicaiton.volatile()并没有崩溃。

是否应该以特定方式处理易失性函数?

调用易失功能的公式在Sheet3上:

=IF(C2="","",IF(OR(...,...,...,...),"Invalid",IF(AND(C2="...",...),"Valid",IF(AND(C2=...,E2<=...),"Valid",IF(AND(C2=...,E2<=...),"Valid",IF(IsIndustryCodeValid(),"Valid","Invalid"))))))

挥发性功能:

Public Function IsIndustryCodeValid() As Boolean
    Application.Volatile
    Dim ValidIndustryCodes() As Variant, IndustryCode As String

    ValidIndustryCodes = Array(33,46,45)
    IndustryCode = Left(Worksheets("Sheet1").Range("A2"), 2)
    i = 0
    For i = LBound(ValidCodes) To UBound(ValidCodes)
        If IndustryCode = ValidIndustryCodes (i) Then
            IsIndustryCodeValid = True
            Exit Function
        End If
    Next

End Function

Workbook BeforeClose Code:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    With Worksheets("Sheet1")

        .Unprotect Password:="password"

            For i = 2 To 10
                If Not .Range("C" & i) = vbNullString Then
                    .Range("C" & i).Locked = True
                End If
            Next i

        .Protect Password:="password"
    End With

End Sub

注意:它的易失性函数崩溃而不是Workbook_Close()。我知道这一点,因为评论Workbook_Close()会在关闭时崩溃。其他评论Application.Volatile在关闭时不会崩溃。

1 个答案:

答案 0 :(得分:1)

我相信(我可能错了)但崩溃的原因是工作簿无法完成所有计算并保存工作簿,因此崩溃了。

您需要让Excel有时间完成它的工作。试试这个。将您的Workbook_BeforeClose更改为此。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    With Worksheets("Sheet1")
        .Unprotect Password:="password"
            For i = 2 To 10
                If Not .Range("C" & i) = vbNullString Then
                    .Range("C" & i).Locked = True
                End If
            Next i
        .Protect Password:="password"
    End With
    ThisWorkbook.Save
    DoEvents
End Sub