Write the First Function
 
 
 

You develop the Gardenpath macro using a series of functions and subroutines. Many subroutines require the manipulation of angles. Because ActiveX specifies angles in radians, but most users think of angles in terms of degrees, begin by creating a function that converts degrees to radians.

To convert degrees to radians

  1. On the command line, enter vbaide, and press ENTER.
  2. In the VBA IDE, on the View menu, click Code to open the Code window.
  3. Enter the following code in the Code window:
    Const pi = 3.14159
    
    ' Convert angle in degrees to radians
    
    Function dtr(a As Double) As Double
    
    	dtr = (a / 180) * pi
    
    End Function
    

    Notice that as soon as you press ENTER after entering the line Function dtr(a As Double) As Double,End Function is added automatically. This ensures that all subroutines and functions have an associated End statement.

    Now look at the code. First, the constant pi is defined as the value 3.14159. This allows you to use the word pi instead of typing 3.14159 each time you need to use the value.

    Next, you are defining a function called dtr (short for degrees to radians). The function dtr takes one argument, a, which is the angle in degrees. The result is obtained by dividing the angle in degrees by 180, and then multiplying this value by pi. The line that begins with a single quote is a comment; VBA ignores all text on a line after a single quote.

    This function can now be used in other subroutines throughout your project.

  4. Save your work. Click File Save Global1. Name the project gardenpath.dvb.

Next, add a function to calculate the distance between points.

To calculate the distance between two points

  1. Enter the following code after the dtr function:
    ' Calculate distance between two points
    
    Function distance(sp As Variant, ep As Variant) _
    
     As Double
    
    	Dim x As Double
    
    	Dim y As Double
    
    	Dim z As Double
    
    	x = sp(0) - ep(0)
    
    	y = sp(1) - ep(1)
    
    	z = sp(2) - ep(2)
    
    	distance = Sqr((Sqr((x ^ 2) + (y ^ 2)) ^ 2) + (z ^ 2))
    
    End Function
    
  2. Save your work.