如何计算给定的字符串计算表达式,如“ 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