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.
- At the AutoCAD Command prompt, enter vbaide.
- In the VBA IDE, Project Explorer window, select the ThisDrawing class module or a code module in the project.
- On the menu bar, click View menu
Code to open a code window for the ThisDrawing class module.
- On the menu bar, click Insert menu
Procedure to create a new procedure in the project.
- In the Add Procedure dialog box, Name text box, type HelloWorld.
- Under the Type section, select Sub.
- Under the Scope section, select Public. Click OK.
- 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")
- 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.