Stop VBA Evaluate from calling target function twice

后端 未结 6 879
自闭症患者
自闭症患者 2020-12-06 06:45

I am having trouble getting VBA\'s Evaluate() function to only execute once; it seems to always run twice. For instance, consider the trivial example below. If we run the Ru

6条回答
  •  旧时难觅i
    2020-12-06 07:26

    I did a quick search and found that others have reported similar behavior and other odd bugs with Application.Evaluate (see KB823604 and this). This is probably not high on Microsoft's list to fix since it has been seen at least since Excel 2002. That knowledge base article gives a workaround that may work in your case too - put the expression to evaluate in a worksheet and then get the value from that, like this:

    Sub RunEval()
        Dim d As Double
    
        Range("A1").Formula = "=EvalTest()"
        d = Range("A1").Value
        Range("A1").Clear
        Debug.Print d
    End Sub
    
    Public Function EvalTest() As Double
        Dim d As Double
        d = Rnd()
        Debug.Print d
        EvalTest = d + 1
    End Function
    

    I modified your example to also return the random value from the function. This prints the value a second time but with the one added so the second print comes from the first subroutine. You could write a support routine to do this for any expression.

提交回复
热议问题