Exercise: An Introduction to VBA (VBA/ActiveX)

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.

  1. At the AutoCAD Command prompt, enter vbaide and press Enter.
  2. In the VBA IDE, Project Explorer window, select the ThisDrawing class module or a code module in the project.
  3. On the menu bar, click View menu Code to open a code window for the ThisDrawing class module.
  4. On the menu bar, click Insert menu Procedure to create a new procedure in the project.
  5. In the Add Procedure dialog box, Name text box, enter HelloWorld.
  6. Under the Type section, select Sub.
  7. Under the Scope section, select Public. Click OK.
  8. Enter the following code between the lines Public Sub HelloWorld() and End Sub lines.
    ' Create a new drawing
    ThisDrawing.Application.Documents.Add
    
    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)
    
    ThisDrawing.SaveAs("Hello.dwg")
  9. On the menu bar, click Run menu Run Sub/UserForm to execute the HelloWorld subroutine.

    When the subroutine finishes executing, switch to the AutoCAD application window. The text “Hello World!” should be visible in your drawing. The drawing name should be Hello.dwg.