如何计算给定的字符串计算表达式,如“ 1+2*3-4/5+ 6^7” 的值?笔者在使用EXCEL2002 时发现在单元格中可以输入此类表达式,输出的则是计算结果,所以写了一个函数,与大家共享。
'引用microsoft excel 10.0 object library( OR OTHER VERSION)
' add a textbox and a commandbutton to form1
Function result(ByVal x As String)
Dim myobj As Object
Set myobj = CreateObject("excel.sheet")
Set myobj = myobj.Application.ActiveWorkbook.ActiveSheet
myobj.Range("a1").Formula = "= " & x '
result = myobj.Range("a1").Value
If err.Number > 0 Then MsgBox err.Description
Set myobj = Nothing
End Function
Private Sub Command1_Click()
Dim x As String
x = Text1.Text
MsgBox x & "=" & result(x)
End Sub
Private Sub Form_Load()
Text1.Text = "3*9^10-21*256^a" '错误表达式,返回错误信息。你可以改成合法表达式再按单击COMMAND1
End Sub