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z 13", IF(SUM(D3:D6)>1,"A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z 14","no" ))))))))))))))

然后我运行以下 VBA 代码

Private Sub ExecuteFormula()
    Dim sFormula As String, vReturn As Variant
    sFormula = Selection.Formula

    vReturn = Application.Evaluate(sFormula)
    If VarType(vReturn) <> vbError Then
        MsgBox vReturn, vbInformation
    Else
        MsgBox "Error", vbExclamation
    End If
End Sub

然后我得到“错误”。对于较短的公式,它工作得很好,所以我想知道是否有一种方法可以使用 VBA 评估长公式(通常)。

最佳答案

根据Microsoft documentation这是导致错误的原因:

Parameters

Name: Name

Required/Optional: Required

Data Type: Variant

Description: A formula or the name of the object, using the naming convention of Microsoft Excel. The length of the name must be less than or equal to 255 characters.

请注意,在描述中它还说您可以使用“对象的名称”而不是公式。

然而,进一步阅读将有助于缩小评估长公式的选项范围。下一节将向我们介绍此方法可以使用的“名称”:

The following types of names in Microsoft Excel can be used with this method:

  • Formulas.
  • A1-style references. You can use any reference to a single cell in A1-style notation. All references are considered to be absolute references.
  • Ranges. You can use the range, intersect, and union operators (colon, space, and comma, respectively) with references.
  • Defined names. You can specify any name in the language of the macro.
  • External references. You can use the ! operator to refer to a cell or to a name defined in another workbook — for example, Evaluate("[BOOK1.XLS]Sheet1!A1").
  • Chart Objects. You can specify any chart object name, such as "Legend", "Plot Area", or "Series 1", to access the properties and methods of that object. For example, Charts("Chart1").Evaluate("Legend").Font.Name returns the name of the font used in the legend.

然后是具体的例子:

[a1].Value = 25 
Evaluate("A1").Value = 25 
 
trigVariable = [SIN(45)] 
trigVariable = Evaluate("SIN(45)") 
 
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1] 
Set firstCellInSheet = _ 
    Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")

所有这些都告诉我们,我们可以使用单元格的地址来执行计算,而不是引入整个公式。

这意味着我们可以修改您的 sub 以使用单元格地址:

Private Sub ExecuteFormula()
    Dim sFormula As String, vReturn As Variant
    sFormula = Selection.Address ' use the cells address not the formula

    vReturn = Application.Evaluate(sFormula)
    If VarType(vReturn) <> vbError Then
        MsgBox vReturn, vbInformation
    Else
        MsgBox "Error", vbExclamation
    End If
End Sub

关于VBA - 在长公式上使用 Application.Evaluate 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267826/

相关文章:

excel - 当数百设置为0时更改excel中行的高度

Excel VBA,使用评估(MAX(IF))条件的自定义搜索 - 不匹配错误

Excel 索引匹配数组 - 显示列表中的所有值

sql - 在 MS Access 查询中使用多值字段

excel - 导入兼容模式工作簿时遇到问题

VBA循环通过工作表运行代码不循环或循环但不运行代码

excel - 复制表格时出错,但复制范围时出错 Excel VBA

vba - 如何将数据从csv文件复制到其他excel文件

javascript - 如何实现Excel的ACCRINT

excel - 高级 Excel Sumif(可能需要 VBA)