View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.misc
Ron Rosenfeld Ron Rosenfeld is offline
external usenet poster
 
Posts: 5,651
Default How to do for this kind of formula?

On Mon, 11 Jun 2007 20:00:01 -0700, kelvin
wrote:

Suppose Cell: A1 = "1+2+3"
and any method to get its result(6) in Cell A2


You can use a UDF.

How involved depends on the variety of what might be in A1.

If just quote marks, numbers and operators, then you can use something simple:

<alt-F11 opens the VB Editor.

Ensure your project is highlighted in the project explorer window, then
Insert/Module and paste the code below into the window that opens:

=============================
Function Eval(rg)
Dim str As String
str = Replace(rg.Text, """", "")
Eval = Evaluate(str)
End Function
=============================

A2: =Eval(A1)

However, if there might be characters other than quote marks and the various
operators, then you need to strip them all out:

==========================================

Function Eval(rg)
Dim str As String

'ensure contains only numbers and operators
Dim oRegex As Object
Set oRegex = CreateObject("VBScript.RegExp")

With oRegex
.Global = True
.Pattern = "[^-0-9+/*^\()]"
End With

str = oRegex.Replace(rg.Text, "")
Eval = Evaluate(str)

End Function
=========================

--ron