The VBA Cos function returns the cosine of a supplied angle.
The syntax of the function is:
Where the supplied Number is the angle (in radians) that you want to calculate the cosine of.
In the following example, the VBA Cos function is used to return the cosine of three different angles (which are expressed in radians).
' Calculate the cosine of three different angles (supplied in radians).
Dim val1 As Double
Dim val2 As Double Dim val3 As Double
val1 = Cos( -3.14159265358979 )
' The variable val1 is now equal to -1.
val2 = Cos( 0 )
val3 = Cos( 0.785398163397448 )' The variable val2 is now equal to 1. ' The variable val3 is now equal to 0.707106781186548. |
In the above VBA code:
If the angle that you want to calculate the cosine of, is expressed in degrees, this must be converted into radians, by multiplying by π/180, before it is supplied to the Cos function. This is shown in the following example:
' Calculate the cosine of 45 degrees.
Const pi = 3.14159265358979
' Convert 45 degrees to radians by multiplying by pi/180.Dim val1 As Double val1 = Cos( 45 * pi / 180 ) ' The variable val1 is now equal to 0.707106781186548. |
In the above VBA code, the angle 45 degrees is converted to radians before it is supplied to the Cos function.
The VBA Cos function then returns the value 0.707106781186548.
Note that, in order to clarify the code, the value 3.14159265358979 (π) has been assigned to the constant, pi, which is used in the calculation.
If the Cos function is supplied with a value that cannot be interpreted as a number, it will return the error: