Writing the Utility Functions

When writing a program, it is beneficial to write small logical subroutines that can be repurposed for other programs. The Gardenpath macro is defined using a series of primary and secondary (utility) functions and subroutines.

Many of the objects added to a drawing require the input or manipulation of angular values. Angles in a drawing are stored in radians and as a result, the methods in the AutoCAD COM library require angular values in radians. However, most users think in degrees and not radians, so it is important to prompt the user for degrees and then handle the conversion to radians in the code.

Converting Degrees to Radians

The following formula is used to convert degrees to radians:

(decimal_angle / 180) * π

In the following steps, you define a function named dtr that accepts an angular measurement in decimal degrees and returns it in radians.

  1. At the AutoCAD Command prompt, enter vbaide.
  2. In the VBA IDE, on the menu bar, click View Code to open a Code window for the ThisDrawing module.
  3. In the Code window, type the following code:
    ' Declare a constant double variable
    Const pi = 3.14159
    
    ' Converts an angular measurement in degrees to radians
    ' Usage: val = dtr(90)
    Function dtr(a As Double) As Double
      dtr = (a / 180) * pi
    End Function
  4. Click File Save Global1.
  5. In the Save As dialog box, in the File Name text box, enter gardenpath and specify a location for the project. Click Save.

Calculating the Distance Between Two Points

In the following steps, you define a function named distance that accepts two 3D points and returns a double value which is the calculated distance between the two 3D points. The value returned can be helpful in determining the midpoint along a given axis.

  1. In the Code window, click after the End Function statement of the dtr function and press Enter twice.
  2. Type the following code:
    ' Calculate distance between two points
    ' Usage: val = distance(point1, point2)
    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
  3. Save the project.