Textbox Calculator (1 Viewer)

rosdi

New member
Local time
Today, 15:00
Joined
Feb 20, 2018
Messages
6
I'm referring to QuickBooks accounting software on how they created a calculator to a textbox.

Searching around, I found a link (cannot add to this post) to try but failed.

Any help?

Code:
Function Calculator()
'
' Author: Markus G Fischer, Geneva, April 2011
'
' Purpose: Allow simple calculations to be evaluated in a numeric text box.
' For example, the user types "2^2*3^3=" and "108" is inserted as value.
'
' This is a perfect job for Eval(), which calls Jet's expression evaluator,
' so that any expression understood in a query or as control source of a control
' will be accepted. The trigger is the "=" sign at the end of the text; when
' typed alone it will recall the last valid expression.
'
' Error management is minimal, a brief flash of red...
'
' Usage: enter "=Calculator()" as change event handler of any text box.
'
    Static sstrRecall As String
    Dim strExpr As String
    Dim dblResult As Double
    Dim txt As TextBox
    Dim i As Integer
    
On Error GoTo BadMath
    
    Set txt = Screen.ActiveControl
    If txt.Text = "=" Then
        If Len(sstrRecall) = 0 Then sstrRecall = "1+2+3+4"
        txt.Text = sstrRecall
    ElseIf Right(txt.Text, 1) = "=" Then
        strExpr = Left(txt.Text, Len(txt.Text) - 1)
        dblResult = Eval(strExpr)
        If Not IsNumeric(strExpr) Then sstrRecall = strExpr
        txt.Text = dblResult ' Round(dblResult, 2)
        txt.SelLength = 100
    End If
    Exit Function
    
BadMath:
    If txt Is Nothing Then
        ' called from wrong event?
    ElseIf Err.Number <> 2113 Then
        dblResult = txt.BackColor
        txt.BackColor = &H6666FF
        For i = i To 10: DoEvents: Next
        txt.BackColor = dblResult
        SendKeys "{BACKSPACE}"
    End If
    Err.Clear
    
End Function
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 15:00
Joined
May 7, 2009
Messages
19,230
Yiu can search calculatie in vb. Vb is close to vba.
 

bob fitz

AWF VIP
Local time
Today, 08:00
Joined
May 23, 2011
Messages
4,719
The function appears to work. What exactly is the problem that you have?
 

isladogs

MVP / VIP
Local time
Today, 08:00
Joined
Jan 14, 2017
Messages
18,212
Attached is a very simple working calculator

 

Attachments

  • Calculator.PNG
    Calculator.PNG
    5.4 KB · Views: 144
  • Calculator.zip
    24 KB · Views: 96

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 15:00
Joined
May 7, 2009
Messages
19,230
Forthe code you posted has instruction on it. For it to work you must call it from the Change Event of the textbox. Type it directly Proprety Sheet->Event

On Change =Calculator()
 

Users who are viewing this thread

Top Bottom