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?
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