In the previous lesson, we have learned how to write code using various mathematical functions in Excel VBA. In this lesson, we shall proceed to learn how to work with trigonometric functions. The three basic trigonometric functions are Sin, Cos and Tan which stand for sine, cosine, and tangent. We also deal with the inverse of tangent, Atn.
The Sin function returns the sine value of an angle. We need to convert the angle to radian as Excel VBA cannot deal with the angle in degree. The conversion is based on the following equation:
π radian= 180o
so 1o=π/180 radian
The issue is how to get the exact value of p? We can use p=3.14159 but it will not be accurate. To get the exact value of π, we use the arctangent function, i.e. is Atn. Using the equation tan(π/4)=1, so Atn(1)=π/4, therefore, π=4Atn(1)
The syntax of the Sin function in Excel VBA is
Sin(Angle in radian)
In this example, we use pi to represent π and assign the value of π using the formula pi = 4*.Atn(1). We use the function Round the value of sine to four decimal places.
Private Sub CommandButton1_Click() Dim pi As Single pi = 4*.Atn(1) MsgBox("Sin 90 is" & Round(Sin(pi/2), 4)) End Sub
Running the program produces the message as shown in Figure 7.1
The Cos function returns the cosine value of an angle
The syntax of the Cos function in Excel VBA is
Cos(Angle in radian)
Private Sub CommandButton1_Click() Dim pi As Single pi = 4*.Atn(1) MsgBox("Cos 60 is" & Round(Cos(pi/3), 4)) End Sub
Running the program produces the message as shown in Figure 7.2