Excecl VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us
≡

Scientific Calculator


In this example, we will enhance the basic features of the calculator and upgrade it to a scientific calculator. We use back the same design as the basic calculator, and add eddtional command buttons.

The additonal command buttons cater for the following mathematical functions:

The design UI is as follows:

The Scientific Calculator Design UI

The Code for the Sine function

Private Sub Cmd_Sin_Click()

f = Val(Lbl_Panel.Caption)
If inv = False Then

sinx = Round(Sin(f * 4 * Atn(1) / 180), 4)
Lbl_Panel.Caption = sinx
Exit Sub

Else

On Error GoTo error_handler

arcsinx = Round((WorksheetFunction.Asin(f) * 180) / (4 * Atn(1)))

Lbl_Panel.Caption = arcsinx
inv = False

Exit Sub
End If

error_handler:
MsgBox ("Please enter a number less than or equal to 1 or more than or equal to -1")

newNum = True

End Sub

Notice that we need to add an error_handler to handle the error when the user entered a value outside the range of 1 and -1 for arcsine. Besides that, we need to use the syntax

WorksheetFunction.Asin(x)
instead of just Asin. For the value of π, we use the formula 4 * Atn(1) because tan(π/4)=1.

The Code for the Cosine function

Private Sub Cmd_Cos_Click()
f = Val(Lbl_Panel.Caption)
If inv = False Then

cosx = Round(Cos(f * 4 * Atn(1) / 180), 4)
Lbl_Panel.Caption = cosx
Exit Sub

Else

On Error GoTo error_handler

arccosx = Round((WorksheetFunction.Acos(f) * 180) / (4 * Atn(1)))

Lbl_Panel.Caption = arccosx
inv = False

Exit Sub
End If

error_handler:
MsgBox ("Please enter a number less than or equal to 1 or more than or equal to -1")

newNum = True
End Sub

The Code for the Tan function

Private Sub Cmd_Tan_Click()
Lbl_Panel.Caption = tanx
If inv = False Then
f = Val(Lbl_Panel.Caption)
tanx = Round(Tan(f * 4 * Atn(1) / 180), 4)

Else

arctanx = Round(Atn(f) * 180) / (4 * Atn(1))

Lbl_Panel.Caption = arctanx

End If

newNum = True
inv = False
End Sub

The Code for the natural Logarithm function

Private Sub Cmd_Ln_Click()

f = Val(Lbl_Panel.Caption)
Lbl_Panel.Caption = Str(Log(f))

newNum = True
inv = True

End Sub

The Code for the Log base 10 function

Private Sub Cmd_Log_Click()
f = Val(Lbl_Panel.Caption)
Lbl_Panel.Caption = Str(Log(f) / Log(10))
newNum = True
End Sub

We declare a variable inv as a boolean to invert betwee Sine and arcsine, cosine and arccosine as well as tan and arctangent.

The Scientific Calculator Runtime UI





Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page