如何检查VBA公式是否正确

发布于 2024-12-11 07:12:55 字数 180 浏览 0 评论 0原文

我正在创建一个 VB 宏,它将“1+1”等字符串值转换为公式。

   Cells(1, 1).Formula = "=" & Cells(1, 1).Value

但如果无法计算值字符串,则会出现运行时错误“1004”。

我如何确定字符串会成功转换为公式?

I'm creating a VB macro that converts string values like "1+1" to formulas.

   Cells(1, 1).Formula = "=" & Cells(1, 1).Value

But if Value string can't be calculated i have Run-time Error '1004'.

How can i be sure that string would convert to formula successfully?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

素罗衫 2024-12-18 07:12:55

首先构造公式,然后对其使用 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

First construct the formula and then use the Evaluate method on it. If it doesn't return an error then you can add it to the cell.

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
内心旳酸楚 2024-12-18 07:12:55

使用 Evaluate 有 2 个问题:

  1. 您无法判断公式在语法上是否无效,或者只是一个当前返回错误值的有效公式(例如 =na()),
  2. 调用 Evaluate 会产生副作用。它可能会调用计算事件,可能会导致计算单元格中的值,即使 Application.Calculate 设置为手动也是如此。

更好的方法是使用 Application.ConvertFormula 并查看是否返回错误。使用:

 If IsError(Application.ConvertFormula(sFormula, xlA1, xlA1, , rngCell)) Then ...

Using Evaluate has 2 issues:

  1. you can't tell whether a formula is syntatically invalid, or just a valid formula that currenly returns an error value (such as =na())
  2. calling Evaluate has side effects. It may call Calculate events, it may cause values in cells to be calculated, even when Application.Calculate is set to manual.

A better approach is to use Application.ConvertFormula and see if that returns an error. Use:

 If IsError(Application.ConvertFormula(sFormula, xlA1, xlA1, , rngCell)) Then ...
固执像三岁 2024-12-18 07:12:55

如果您需要对单元格的值进行完全验证,那么正则表达式模式可能就是这样的 - 这将确保仅使用与您想要的模式匹配的单元格(放置等号可能仍然适用于具有不良格式的单元格,并且您可能想避免这种情况,因为跟踪更改将很困难)。

可以安全地假设这应该适用于带有某种运算符(例如加号或减号)的数值数据吗?

If you need to do full validation of the cell's value then a regex pattern might just be the thing - that'll ensure that only cells matching the pattern you want are used (placing an equal sign might still work in cells with indesirable formats and you might want to avoid that since tracking the changes will be hard).

Is it safe to assume that this should apply to numerical data with some kind of operator like plus or minus?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文