The VBA Cos Function

Related Functions:
VBA Sin
VBA Tan

Description

The VBA Cos function returns the cosine of a supplied angle.

The syntax of the function is:

Cos( Number )

Where the supplied Number is the angle (in radians) that you want to calculate the cosine of.


VBA Cos Function Examples

Example 1

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 )
' The variable val2 is now equal to 1.
val3 = Cos( 0.785398163397448 )
' The variable val3 is now equal to 0.707106781186548.

In the above VBA code:


Example 2

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
Dim val1 As Double
' Convert 45 degrees to radians by multiplying by pi/180.
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.


VBA Cos Function Error

If the Cos function is supplied with a value that cannot be interpreted as a number, it will return the error:

Run-time error '13': Type mismatch

VBA Run Time Error 13 Message Box