计算string作为vba中的公式

我试图评估包含数据的Excel单元格,

“AAA * 2”

然后在vba试图解决他们使用,

dim AAA dim equation dim result AAA=inputbox("?") 'some numeric value equation=sheets("sheet1").range("A1").value 'contains "AAA*2" result=application.evaluate("=" & equation) 

我不知道是否有这样的可能。如果是这样,这将使我目前的项目方式更简单。感谢任何帮助事先。

你不能混用vba和string。

添加equation = replace(equation,"AAA", AAA)

 dim AAA dim equation dim result AAA=inputbox("?") 'some numeric value equation=sheets("sheet1").range("A1").value 'contains "AAA*2" equation = replace(equation,"AAA", AAA) result=application.evaluate("=" & equation) 

声明你的types,并注意你对所涉及的值做出的隐含假设。

 Dim userInput As Variant userInput = InputBox("?") ' could be numeric, could be a null string pointer, could be anything. If Not IsNumeric(userInput) Then Exit Sub Dim AAA As Double AAA = CDbl(userInput) Dim source As Worksheet Set source = ThisWorkbook.Worksheets("Sheet1") Dim sourceEquation As Variant sourceEquation = source.Range("A1").Value ' could be an error, an empty variant, a date, whatever If IsError(sourceEquation) Then Exit Sub Dim equation As String 'the "AAA" in the string is a string literal, doesn't refer to this local AAA variable. equation = VBA.Strings.Replace(CStr(sourceEquation), "AAA", AAA) Dim result As Double result = Application.Evaluate("=" & equation)