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"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的長公式(通常)。

回答

3

按照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