gpt4 book ai didi

vba - VBA 声明波动性的工作原理

转载 作者:行者123 更新时间:2023-12-02 21:48:18 24 4
gpt4 key购买 nike

我有一种情况,我希望一个函数是“部分” volatile 的 - 也就是说,在它不再返回错误之前是 volatile 的,此时除非其参数之一发生更改(即标准),否则将不再计算它非脏波动)。

到目前为止,我已经尝试了三种方法,但都不起作用。谁能提出其他建议吗?

方法 1: IF 条件下的 Application.Volatile

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 陷入无限循环

我还尝试在存储为 ThisWorkbook 属性的字典中跟踪 rngThis,其中参数是字符串而不是范围(范围通过 Range(strThisCell)),并且仅在函数中尚未设置 dirty 时才设置 dirty,这会打破无限循环,但一旦调用 rngThis.Dirty 也会返回 #VALUE!

最佳答案

第一个代码在我这边工作,但您需要将计数器放在 If 语句 中,如下所示:

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 语句 中,效果是一样的。

编辑1:关闭 volatile

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

关于vba - VBA 声明波动性的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com