Search Tools Links Login

Evaluate Equation


Evaluate any Mathematical Equation
like: Evaluate("(5+3)*2")

Original Author: Lefteris Eleftheriades

Code

Function Evaluate(ByVal Equation As String)
Dim i&, P%, Si&
Equation = Replace(Replace(Equation, ",", "."), "--", "")
'Parenthesis Begins with outermost
For i = 1 To Len(Equation)
  If Mid(Equation, i, 1) = "(" Then
  P = P + 1
  If P = 1 Then Si = i
  End If
  If Mid(Equation, i, 1) = ")" Then
  If P = 1 Then
   Evaluate = Evaluate(Mid(Equation, 1, Si - 1) & Evaluate(Mid(Equation, Si + 1, i - 1 - Si)) & Mid(Equation, i + 1))
   Exit Function
  End If
  P = P - 1
  End If
Next

'Addition / Substruction
  For i = Len(Equation) To 1 Step -1
   If Mid(Equation, i, 1) = "+" Then
    If i > 1 Then
      If Mid(Equation, i - 1, 1) <> "*" And Mid(Equation, i - 1, 1) <> "/" Then
       Evaluate = Evaluate(Mid(Equation, 1, i - 1)) + Evaluate(Mid(Equation, i + 1))
       Exit Function
      End If
    Else
      Evaluate = Evaluate(Mid(Equation, 1, i - 1)) + Evaluate(Mid(Equation, i + 1))
      Exit Function
    End If
   End If
   If Mid(Equation, i, 1) = "-" Then
    If i > 1 Then
      If Mid(Equation, i - 1, 1) <> "*" And Mid(Equation, i - 1, 1) <> "/" Then
       Evaluate = Evaluate(Mid(Equation, 1, i - 1)) - Evaluate(Mid(Equation, i + 1))
       Exit Function
      End If
    Else
      Evaluate = Evaluate(Mid(Equation, 1, i - 1)) - Evaluate(Mid(Equation, i + 1))
      Exit Function
    End If
   End If
  Next

'Multiplication / Division
For i = Len(Equation) To 1 Step -1
  If Mid(Equation, i, 1) = "*" Then
  Evaluate = Evaluate(Mid(Equation, 1, i - 1)) * Evaluate(Mid(Equation, i + 1))
  Exit Function
  End If
  If Mid(Equation, i, 1) = "/" Then
  Evaluate = Evaluate(Mid(Equation, 1, i - 1)) / Evaluate(Mid(Equation, i + 1))
  Exit Function
  End If
Next

Evaluate = Val(Equation)
End Function

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 129 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.