VBA如何声明挥发性的作品
我有一种情况,我希望一个函数是“部分”易失性的 – 也就是说,它是不稳定的,直到它不再返回一个错误,此时不再计算,除非它的一个参数改变了(即标准非脏挥发性)。
到目前为止,我已经尝试了三种方法,其中没有一种可行。 任何人都可以提出其他build议
方法1: Application.Volatile在IF条件下
Public Function VolTest() As Long Static lngCounter as Long If lngCounter < 5 Then Application.Volatile End If lngCounter = lngCounter + 1 VolTest = lngCounter End Function
结果:计数器继续计数超过5(我相信它应该停在5)
方法2: Application.Volatile在单独的被调用的函数中并不总是被调用
Public Function VolTest() As Long Static lngCounter as Long If lngCounter < 5 Then lngCounter = VolTest_VolatileIncrememnt(lngCounter) Else lngCounter = VolTest_NonVolatileIncrememnt(lngCounter) End If VolTest = lngCounter End Function Public Function VolTest_NonVolatileIncrememnt(lngCounter As Long) As Long VolTest_NonVolatileIncrememnt = lngCounter + 1 End Function Public Function VolTest_VolatileIncrememnt(lngCounter As Long) As Long Application.Volatile VolTest_VolatileIncrememnt = lngCounter + 1 End Function
结果:方法1
方法3: 传入当前单元格,如果尚未达到,则设置为脏
Public Function VolTest(rngThis as Excel.Range) As Long Static lngCounter as Long If lngCounter < 5 Then rngThis.Dirty End If lngCounter = lngCounter + 1 VolTest = lngCounter End Function
结果:Excel在无限循环中挂起
我也试着跟踪rngThis,其中参数是一个string而不是范围(范围通过Range(strThisCell)
),存储在ThisWorkbook属性的字典中,并且只有在函数中已经设置了脏,这打破了无限循环,但也返回#VALUE!
只要rngThis.Dirty
被调用。
第一个代码在我的结尾工作,但是你需要把这个计数器放在If Statement
像这样:
Public Function VolTest() As Long Static lngCounter As Long If lngCounter < 5 Then Application.Volatile lngCounter = lngCounter + 1 End If VolTest = lngCounter End Function
它仍然是不稳定的,但价值只会变化到5。 如果你在上面声明Application.Volatile
,但是再把计数器放在If Statement
里,也是一样的。
编辑1:closures易失性
Public Function VolTest() As Long Static lngCounter As Long If lngCounter < 5 Then Application.Volatile (True) lngCounter = lngCounter + 1 Else Application.Volatile (False) End If VolTest = lngCounter MsgBox "Called" ' to test if it is turned off End Function