Perform an Introductory Exercise

Now that you have learned the basics of programming in AutoCAD VBA, let's try creating a simple “Hello World” exercise. In this exercise you will create a new AutoCAD drawing, add a line of text to that drawing, then save the drawing, all from VBA.

To create the “Hello World” text object

  1. Open the VBA IDE by entering the following command from the AutoCAD command line:

    Command: VBAIDE

  2. Open the Code window by selecting the Code option from the View menu in the VBA IDE.
  3. Create a new procedure in the project by selecting the Procedure option from the Insert menu in the VBA IDE.
  4. When prompted for the procedure information, enter a name such as HelloWorld. Make sure the Type selected is Sub, and the Scope selected is Public.
  5. Choose OK.
  6. Enter the following code (that opens a new drawing) between the lines Public Sub HelloWorld() and End Sub.
  7. Enter the following code (that creates the text string and defines its insertion location) immediately following the code entered in step 6.
    Dim insPoint(0 To 2) As Double 'Declare insertion point
    Dim textHeight As Double	 'Declare text height
    Dim textStr As String		'Declare text string
    Dim textObj As AcadText		'Declare text object
    insPoint(0) = 2	'Set insertion point x coordinate
    insPoint(1) = 4	'Set insertion point y coordinate
    insPoint(2) = 0	'Set insertion point z coordinate
    textHeight = 1				'Set text height to 1.0
    textStr = "Hello World!"		'Set the text string
    'Create the Text object
    Set textObj = ThisDrawing.ModelSpace.AddText _
    						(textStr, insPoint, textHeight)
  8. Enter the code (that saves the drawing) immediately following the code entered in step 7.
  9. Run your program by selecting the Run Sub/UserForm option from the Run menu in the VBA IDE.

    When the program finishes running, bring the AutoCAD application to the front. You should see your text “Hello World!” visible in your drawing. The drawing name should be Hello.dwg.