Non-volatile UDF always recalculating

前端 未结 2 634
臣服心动
臣服心动 2021-02-06 11:49

I am trying to make a non-volatile UDF but it seems not possible. So here is a my very simple test-UDF:

Option Explicit
Dim i As Integer

Sub Main()

i = 0
[A1]         


        
2条回答
  •  灰色年华
    2021-02-06 12:30

    I found the solution, and it is indeed a very simple one but also made this hard to debug: If you make any change to your VBA code all the UDF get flagged for recalculation! I modified the degug code of David:

    Sub main()
    
    'nothing depends on the Value in [A13]
    [A13] = "" 
    [A13] = "hgdg"
    [A13] = ""
    i = 46
    
    End Sub
    
    Function f_appvol(rng As Range)
    
    Application.Volatile
    Debug.Print "f_appvol"
    
    f_appvol = rng.Value
    End Function
    
    Function f_appNOTvol(rng As Range)
    Application.Volatile (False)
    Debug.Print "f_appNOTvol"
    
    f_appNOTvol = rng.Value
    End Function
    
    Function f_omit(rng As Range)
    
    Debug.Print "f_omit"
    f_omit = rng.Value
    
    End Function
    

    After entering the code and running it for the first time, only f_appvol is recalculated. If you now change i=46 to i=47 and execute it, all the UDF get recalculated. All subsequent runs after that first run after the change give the expected behaviour.

提交回复
热议问题