如何检查VBA公式是否正确

yur*_*15t 2 excel vba excel-2007

我正在创建一个VB宏,将字符串值(如"1 + 1")转换为公式.

   Cells(1, 1).Formula = "=" & Cells(1, 1).Value
Run Code Online (Sandbox Code Playgroud)

但如果无法计算值字符串,我有运行时错误'1004'.

我怎样才能确定字符串是否会成功转换为公式?

Tim*_*ams 6

首先构造公式,然后对其使用Evaluate方法.如果它没有返回错误,那么您可以将其添加到单元格.

Sub tester()
    Dim f As String

    f = "1+1"
    Debug.Print f, IIf(FormulaOK(f), "OK", "not valid")

    f = "1blah1"
    Debug.Print f, IIf(FormulaOK(f), "OK", "not valid")

End Sub

Function FormulaOK(f As String) As Boolean
    FormulaOK = Not IsError(Application.Evaluate(f))
End Function
Run Code Online (Sandbox Code Playgroud)