0% found this document useful (0 votes)
132 views

Complete Customisable Programming Workbook For Autocad

This document provides instructions for creating a basic "Hello World" program using Visual Basic for Applications (VBA) integrated into AutoCAD. It describes launching the VBA IDE, inserting a user form, adding a command button, writing code within the button's click event to display a message box with the text "Hello World", and saving the program. The purpose is to demonstrate the basic syntax and workflow of creating a simple VBA program within the AutoCAD environment.

Uploaded by

Liam McCann
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

Complete Customisable Programming Workbook For Autocad

This document provides instructions for creating a basic "Hello World" program using Visual Basic for Applications (VBA) integrated into AutoCAD. It describes launching the VBA IDE, inserting a user form, adding a command button, writing code within the button's click event to display a message box with the text "Hello World", and saving the program. The purpose is to demonstrate the basic syntax and workflow of creating a simple VBA program within the AutoCAD environment.

Uploaded by

Liam McCann
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Department of Engineering Course title: HND Computer Aided Draughting and Design

Unit: Title:

DW 216 35 Customised Programming for CAD

As the VBAIDE is integrated into AutoCAD, ensure the host package has been initiated before continuing with this exercise.

When launched for the first time, the VBAIDE (Visual Basic for Applications Integrated Development Environment) greets the user with a bewildering array of menus and windows.

The basic functions of the most common features are explained below.

As the VBAIDE begins with an empty interface, to fully describe the function of the different elements within the environment we need to insert a user form. This will activate the different windows, displaying relevant data. Inserting a form To begin designing and constructing a program, we must first insert a form. This acts as a design board, a place to design and attach controls. Step 1
Open the Insert menu and choose UserForm. Two new objects appear. The first titled UserForm is the form, program designers use this to graphically construct the user interface.

The second object, titled Toolbox, contains various objects (controls) you can add to the form.

First, look at the new form's name: UserForm1. Every VBA project, every form and module within the project, and every object on every form has a name. When you start a project, add a new form to the project, or add a new object to the form, VBA constructs a default name.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Get into the habit of changing these default names to something more meaningful to you and everyone else that uses your program. Once a program has been created, it could be some time before it needs to be modified, so all the names used throughout your program must be instantly recognisable.

Step 2 Project window


First find the window titled Project. This is referred to simply as the project window and displays all the projects currently loaded into all drawings that are open.

With a similar environment to Windows Explorer, this window not only allows the user to keep track of (and access quickly) specific forms or modules using a hierarchal system, but also allows programs to be run on more than one drawing.
Using the project window, select ACADProject(Global1). Right click to invoke the shortcut menu, and select ACADProject properties... to initiate the Project Properties dialogue box.

Change the project name to vbaDemo. You can add a description of the program within the Project Description section, however it is more professional to add a comment block at the beginning of the code (see Example 1.1).

The other option Help File Name: allows the application developer to create a custom help file and link to it here (other software may be required).

The first three letters are called the prefix and almost every object in VBA has a prefix informing the user of the type of object it is created from (see prefix handout). After the prefix is the objects name, it MUST be something meaningful.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering The project window has been updated, it has added a folder titled forms and stored the form in this folder (it has not been saved, and as such if the program is shutdown before the user saves it, all data will be lost, including the form).

Step 3

The default name for the new form is UserForm1, change this using the name section of the properties window to frmDemo. Again using the prefix to identify the object as a FoRM.

Forms are your main interface with the user. Additionally, any time you ask the user for more than two or three pieces of information, consider using a form rather than command line prompts.

Properties window
The properties window will display the relevant properties of the current selected object. It will change which data is displayed each time a different item is selected.

It allows the user to name controls and forms etc. and also the values associated with these items, e.g. caption, width, height, location and colour etc.

Adding controls
Step 1 To add a command button, select the command button icon from the toolbox and using the forms grid and snap function click and drag on the form to create the button.

Step 2

Press run to test the form and button within the AutoCAD window. Nothing happens when the button is pressed? That is because we have not told the button how to respond to being pressed.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 3
Press the close button on the form (top right cross) to return to the form design window. Double click the button to activate the code window. This is where the code is added, giving a set of instructions to be executed only if the button is pressed.

NOTE the beginning and end of the code for this button!!! Private Sub CommandButton1_Click() All the code for this button must be contained within these lines End Sub

(SEE HELLO WORLD PROGRAM TO ADD CODE)

Inserting a module Step 1


Choose insert module from the toolbar

Again a new folder is created in the project window and the module is stored there.

Step 2
If double-clicked the modules code window is invoked, allowing the user to add code which would be accessible from the form, but also kept separately to keep the program from becoming cluttered. More importantly modules of code can be accessed directly by the CAD user without having the VBAIDE open at all!

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Forms
Attach controls On activate, set-up sizes, coordinates etc. On de-activate show other form

Modules
Allow forms to be shown using macro Keep complex sections of code separate

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Booklet 1
The BASIC History, A Short introduction. In 1964, John Kemeny and Tom Kurtz implemented a new compiled language named Beginner's All-purpose Symbolic Instruction Code (BASIC) as a tool for learning the fundamentals of programming. Ten years later Bill Gates and Paul Allen redesigned BASIC as an interpreted language for M.I.T.S.'s Altair kit, making BASIC the first Microsoft product. Over the next few years, BASIC could be found on most Personal Computers, being distributed with DOS as GW-BASIC, making it the de facto standard for the BASIC language when lots of different versions existed. Microsoft took the initiative of distributing a compiler so users could package their code that would be run without an interpreter, making programs more transportable.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

The result, Quick Basic, was simple enough to be used by adults and kids alike for professional purposes or simply for fun. Historically things changed in 1989, as during an interview with BYTE Magazine, Bill Gates promised users a new BASIC, "Future versions of BASIC will increasingly provide support for this kind of programming. The programs will look different from the BASIC we're all used to. A visual BASIC program will be a mixture of code, programmer-written objects, and visually specified objects." Only three years after that interview Microsoft released Visual Basic for Windows and DOS. The DOS version ended at release 1.0 but the Windows version thrived and evolved, becoming the most popular entry level programming language to date, Visual Basic for Applications. But why "For Applications?" This newest version of the BASIC language is integrated into hosting applications like AutoCAD, office etc. This Integrated Development Environment (IDE) is a collection of specialised window interfaces, designed specifically for the hosting package.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 1 Hello World


This short program is historically the first program users should attempt when beginning any new language.

Hello world is the name given to a short program that demonstrates the syntax of the code and in the case of VBA, allows the programmer to get the feel for the IDE (Integrated Development Environment).

As VBA is an integrated package, it requires AutoCAD to be up and running before the IDE can be launched.

Step 1

Launch AutoCAD and start with a new drawing (the 2D standard sheet if available).

Step 2
To start the IDE, hold down Alt + F11

By default the IDE starts with an empty interface, this is to avoid cluttering up the environment (and temporary memory) with several programs open at once.

Step 3

Choose Insert UserForm from the menu bar to add a form to the design window.

The form exists simply as a place to attach any controls required (e.g. buttons, scrollbars etc.)

Step 4

Select the CommandButton icon from the toolbox.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Using the forms grid and snap drawing aid (it may be a while since you last used grid and snap) click and drag to create a command button.

Step 5
Using the properties window, change the following values for the button:

(Name) Caption

cmdHello Hello World

***SEE VBA_ PREFIX EXPLANATION SHEET "W:\CAD\HNDCADR\F216_35_Customised Programming\vba_prefixes.doc

Step 6
Double click the cmdHello button to invoke the code window. The on-click event function is triggered and you will be greeted with

Private Sub cmdHello_Click()

End Sub

Type the following lines of code between the two existing lines use msgbox to inform user MsgBox Hello World, this is my first VBA program.

Step 7

Before running any program, it should be saved to avoid loss of work as a result of errors in the code.

Select File Save Global1 from the menu bar

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Navigate using the explorer to your VBA folder

Save the file as HelloWorld.dvb

Step 8
Select the Run button on the standard toolbar to initiate the program.

The AutoCAD window should become active, and the form you designed visible. If so, press the Hello world button.

CONGRATULATIONS, you have just designed, coded and executed your first AutoCAD VBA program.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 2 Show date and time


This program shows the simplicity of the VBA language while communicating with the operating system to return date and time values.

Step 1
Initiate AutoCAD and open a new drawing

Step 2
Launch the VBAIDE by pressing Alt+F11

Step 3

Insert a user form from the Insert menu

Step 4

Add the following buttons


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Function

Name

Caption

Show date Show time Quit program

CmdDate CmdTime cmdQuit

Date Time Quit

Step 5 Double click the cmdDate button to activate the code window.

Step 6

Type the following code within the subroutine, remembering to use tabs to indent the code (pretty print)

Private Sub cmdDate_Click() Dim MyDate As Date

MyDate = Date MsgBox "Date = " & MyDate, , "Date"

End Sub Step 7 Using the object drop down list box (top left of the code window) select the cmdTime function. Notice how the code window automatically starts a sub routine for that event being triggered by a click.

Step 8 Enter the following code for the cmdTime button (remembering to use tabulation) Dim MyTime as Date
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering MyTime = Time MsgBox "Time = " & MyTime, , "Time" Step 9 Again using the object drop down list, select the cmdQuit button. Enter this code for the function Private Sub cmdQuit_Click() End End Sub Step 10 Remember to save the project before testing the program. Step 11 Test the robustness of your new program by selecting the run button from the standard toolbar. If all is successful you should be able to Display the date Display the time Quit the program to be returned to the VBAIDE

Step 12 Although the program is starting to look good, it is still lacking that commercial touch. Go back to the form design window by double clicking UserForm1 in the project explorer. Ensure the form is selected and change these values (Name) Caption frmTime Show date and time. (change the proportions of the form??)

Step 13 Click once on the cmdDate button and change the following value Accelerator D The fist letter should be underlined, allowing access to the button from the keyboard by pressing Alt + D
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

This will add to the look and feel of the program during runtime. Step 14 Do the same to the other two buttons CmdTime CmdQuit Accelerator = T Accelerator = Q

Step 15 Save the program and run paying attention to the accelerator keys, try them out. Do they work?

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 3
Cup holder program
Sometimes you have to take a break from the more serious aspects of designing and coding programs and just code something you find amusing or interesting. This program has been around the world a few times; however it has the best example of easy interaction with the system while demonstrating the simplicity of the BASIC language. Step 1 Launch AutoCAD Step 2 Initiate the VBAIDE Step 3 Create a form, remembering to name the form (hint frmCupHolder) Step 4 The form should still be selected.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering In the properties window, click in the picture row Select the browse button

Navigate to the CocaCola.BMP supplied by the lecturer. Step 5 The image will display at its original size (too big) Select the PictureAlignment option in the properties window and select number 2 center Step 6 Select the PictureSizeMode option and select number 3 zoom This will keep the pictures proportions, however you can change the size of the form to suit the image. Step 7 Add two buttons to the foot of the form cmdActivate cmdDeactivate

Step 8 Enter the code window and type the code for both buttons Private Sub cmdActivate_Click() Call mciSendString("Set CDAudio Door Open Wait", 0&, 0&, 0&) End Sub Private Sub cmdDeActivate_Click() Call mciSendString("Set CDAudio Door Closed Wait", 0&, 0&, 0&) End Sub

Step 9 Save the program before running to test. Why doesnt it work? We havent declared the function mciSendString, so VBA doesnt recognise the command
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 10 It is good practice to keep the code as understandable as possible (for your future reference and any other programmers who may look at your code), so we will keep the declare function within its own module. Choose Insert Module from the toolbar Rename the module using the properties window Name Declare1

Step 11 Double click the module and enter the following code Public Declare Function mciSendString Lib "winmm.dll"_ Alias "mciSendStringA" _ (ByVal varCommand As String, _ ByVal varReturnString As String, _ ByVal varReturnLength As Long, _ ByVal varCallback As Long) As Long This function uses a Microsoft DLL (dynamic link library) to control the operating system allowing the program to return system information or control hardware. The fact VBA can call upon other Microsoft programs to access system commands means it can keep the rest of the code to a few lines. Save and run the program again.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 4
Get UserName
This program will get return the name of the user (if they are logged in to the system). The programmer could use this information to set system variables to suit this individual. Basic LoggInName method Step 1 Create a from with one button (remember to use good practice and name everything using VBA naming conventions). Form Button Name frmUserName cmdName Caption Get username Display username

Step 2 Enter the following code for a button click event... Private Sub cmdName_Click() Dim varUser As String
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering varUser = ThisDrawing.GetVariable("LOGINNAME") MsgBox varUser End Sub Getvariable returns the value stored agains specific variables, in this case the name of the person logged into the system. Step 3 SAVE the program and run it to test the result is correct (remember you should be logged in with your student number)

LoggInName length method Step 1 Create a from with one button (remember to use good practice and name everything using VBA naming conventions). Form ButtoncmdName Name frmUserName

Get userna Display use

Step 2 Enter the following code for the command button Private Sub cmdName_Click() Dim varUser As String Dim NameLen As Long Dim X As Long varUser = Space(10) name will be 10 characters long NameLen = 10 display all ten characters X = GetUserName(varUser, NameLen) MsgBox "The current user is: " & vbCr & varUser varUser = X End Sub Step 3 Create a module and enter the following code Public Declare Function GetUserName& Lib "advapi32.dll" _ Alias_ "GetUserNameA" (ByVal lpBuffer As String, nSize _ As Long)
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 4 SAVE the program and run it to test the result is correct (remember you should be logged in with your student number)

Program 5 pt i

Reading from a file

Being able to read from a text file while using AutoCAD is a big MUST for any programming language. VBAs simple language makes this very easy for the programmer to understand, allowing more data to be transferred from text file to variables.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering As the function of this program will be to read a text file, we must firstly create that file in Notepad.

Step 1
Using notepad, add the following text (pressing return at the end of each line)

Your first name Your surname HNC/HND CADD Motherwell

Step 2

Save the file as C:\somefile.txt (this is on the C: drive and called somefile.txt)

Step 3
Now the file has been created, launch AutoCAD and initiate the VBAIDE

Step 4
Create a form with 4 buttons Name cmdRead cmdWrite cmdAppend cmdClear Caption Read from file Write to file Append to file Clear file

Remember to name all the buttons, form and project using VBA naming conventions.

NOTE: Not all the buttons will be coded in this tutorial


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 5

Double click the cmdRead button to access the code window and enter the following code

Private Sub cmdRead_Click()

create space for variables Dim varCont As String Dim varChristian As String Dim varSurname As String Dim varLevel As String Dim varCourse As String Dim varAddress As String

'open file for reading Open "c:\somefile.txt" For Input As #1 it is now known as #1

get from file Input #1, varChristian, varSurname, varLevel, varCourse,_ varAddress 'read first line and store in varChristian variable 'read second line and store in varSurname variable etc...

display the first and second items on msgbox MsgBox varChristian & " " & varSurname & " ",_ vbInformation, "Student name"

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering display second and third items MsgBox varLevel & " " & varCourse & " ", vbInformation,_ "Course information."

display fourth item MsgBox varAddress 'no info sign OR TITLE!!!

REMEMBER to close the file (stored as #1) Close #1 End Sub

Step 6

Save the project as TextFile.dvb

Step 7

Run the program from the VBAIDE to launch the form in the AutoCAD window.

Step 8
Press the cmdRead button.

Press OK as the msgboxes display the text from the file before closing the form.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 5 pt ii

Writing to a file

This tutorial will deal with the coding behind the cmdWrite button.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 1
Access the code window for the cmdWrite button

Step 2
Type the following code Private Sub cmdWrite_Click()

Open "c:\somefile.txt" For Output As #1 'open file_ for writing (it is now known as #1)

Print #1, "This will CLEAR existing data and appear_ at the top of the file." 'print in file message

Close #1 'REMEMBER to CLOSE FILE

End Sub

Step 3
Run the program (did you remember to save?)

Step 4
Select the cmdWrite button to write the message to the file

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 5
Open the text file using notepad

Has the text been written to the file?

Where has the other text gone?

Program 5 pt iii

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Clearing a file

This tutorial will deal with the coding behind the cmdClear button.

Step 1
Access the code window for the cmdCLear button

Step 2
Type the following code Private Sub cmdClear_Click()

Open "c:\somefile.txt" For Output As #1 'open file_ for writing (it is now known as #1)

as file is opened for writing, it erases existing data print nothing

Close #1 'REMEMBER to CLOSE FILE

End Sub

Step 3
Run the program (did you remember to save?)

Step 4
Select the cmdClear button to write the message to the file

Step 5

Open the text file using notepad


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Has the text been cleared from the file?

The file was opened for writing, when and how did it delete the existing test?

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Booklet 5 pt iv

Append to a file

This tutorial will deal with the coding behind the cmdAppend button.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering As the last tutorial cleared the file, you will need to add some text to the file before we can append data to it.

Step 1
Run the program

Step 2
Select the write to file button to add a line of text to the file.

Step 3
Close the form to return to the VBAIDE

Step 4

Access the code window for the cmdAppend button

Step 5
Type the following code Private Sub cmdAppend_Click() 'append text to bottom of a text file ' '

Open "c:\somefile.txt" For Append As #1 'open file for_ append (it is now known as #1)

Print #1, "This will leave existing data and appear at_ the bottom of the file." 'print in file message

Close #1 'REMEMBER to CLOSE FILE

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering End Sub

Step 6
Run the program (did you remember to save?)

Step 7
Select the cmdAppend button to append the message to the file

Step 8

Open the text file using notepad

Has the text been appended to the bottom of the file?

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 6
Draw a 2D line
Using VBA to return system variables is advantageous, however the real benefit is in the simplicity of the language while creating objects (also referred to as entities, we know them as line, rectangle, circle etc.) Step 1 Open a new drawing in AutoCAD. Use the actual AutoCAD command ZOOM... set Center: 50,25 Magnification: 100

Step 2 Create a form with one command button Name CmdLine Step 3
Board of Management of Motherwell College: Registered Charity Number SC021206

Caption Draw line

Department of Engineering Enter the code for the button Sub cmdLine_click() Dim lines As AcadLine Dim p1(0 To 2) As Double Dim p2(0 To 2) As Double using an array, we can store the values for x, y and z X stored in (0) Y stored in (1) Z stored in (2) p1(0) = 0 p1(1) = 0 p1(2) = 0 p2(0) = 100 p2(1) = 50 p2(2) = 0 Set lines = ThisDrawing.ModelSpace.AddLine(p1, p2) End Sub Step 4 Save and run the program and press the cmdLine button ONCE. The line doesnt display in the AutoCAD window? It has been created, the window needs to be refreshed (similar to the AutoCAD regen all command) Step 5 Close the form to return to the VBAIDE

Select the AutoCAD window from the taskbar The line should be visible?

Step 6 Erase all the objects in the AutoCAD window and return to the VBAIDE

Step 7

Add the following code to the bottom of the cmdLine function...


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

lines.Update

Step 8

Save and run the program

Press the cmdLine button to create (and display) the line?

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 7
Add circle
Until now all the programs have been initiated using the run button within the VBAIDE.

VBA programs should be loaded and run without opening the VBAIDE (this is reserved for the programmer), by pressing the tools Macro Load project buttons.

To enable this we need to add a module.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 1
Start the VBAIDE and create a form with one button.

Step 2

Add the following code to the cmdCircle button... Private Sub cmdCircle_Click() Dim Radius As Double Dim objCircle As AcadCircle Dim varCP(0 To 2) As Double

Radius = 20 varCP(0) = 0 'x coordinate varCP(1) = 0 'y varCP(2) = 0 'z

Set objPoint = ThisDrawing.ModelSpace.AddPoint(varCP)

Set objCircle = ThisDrawing.ModelSpace.AddCircle(varCP, Radius)

objCircle.Update 'to refresh screen and display circle

End Sub

Step 3
Instead of running the program from the IDE we need to insert a module

Choose insert module from the toolbar

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 4
Double click the module in the project window to access the code window

Step 5

Add the following code... Sub ShowCircleForm() FrmCircle.show End sub Step 6 Save and exit the VBAIDE and Close the active AutoCad drawing Step 7 Open a new drawing Use the actual AutoCAD command ZOOM here set Centre to 0,0 and the Magnification to 100 Step 8 Choose manage load application load Navigate the explorer to the directory containing the circle program Select the circle.dvb program and select open The program has been loaded into the drawing, but still needs to be activated and instructed to run Step 9 Press manage run VBA macro Select the ShowCircleForm macro and press run to start the program. This module instructs VBA to show the form which has the button containing the code which draws our circle: Sub ShowCircleForm() frmCircle.Show End Sub We MUST ensure then, that the form is named frmCircle and not the default Userform1
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Remember: Dont confuse a forms NAME with its CAPTION. Now when we run the module/macro directly from AutoCAD, the user should immediately be presented with frmCircle. We can now use the cmdCircle button to draw the circle.

Program 8
Add rectangle

The visual basic language does not have a command enabling AutoCAD to create a rectangle directly. Instead the program must create a rectangle in the same way AutoCAD does, by drawing a continuous polyline between the four corner points. Step 1
Launch AutoCAD and start with a new drawing (the 2D standard sheet if available).
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Use the actual AutoCAD command ZOOM... set Center: 50,25 Magnification: 100

Step 2
Start the VBAIDE and create a form with one button

Name CmdRectangle FrmRectangle

Caption rectangle Draws a rectangle

Step 3
Insert a module and enter the code required to show the form. It is the same procedure required to show the frmCircle form in the previous exercise. The code should be:

FrmRectangle.Show

Step 4
Enter the following code for the rectangle button: Private Sub cmdRectangle_Click()

Dim objRectangle As AcadLWPolyline Dim varPoint(0 To 7) As Double

varPoint(0) = 0 'split user defined point 1 into x and y varPoint(1) = 0

varPoint(2) = 100 varPoint(3) = 0


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

varPoint(4) = 100 varPoint(5) = 50

varPoint(6) = 0 varPoint(7) = 50

Set objRectangle = ThisDrawing.ModelSpace.AddLightWeightPolyline(varPoint)

objRectangle.Closed = True a closed object objRectangle.Update refresh screen to show rectangle

End Sub

Step 5

Save the project and exit the VBAIDE.

Using AutoCAD, select the tools macros macro button

The ShowRectangleForm macro should be selected, press run to activate the program.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 9
Add triangle
As with the rectangle code, this program will need to draw a continuous polyline between points 1, 2 and 3.

Step 1

Launch AutoCAD and start with a new drawing (the 2D standard sheet if available). Use the actual AutoCAD command ZOOM... set Center: 50,25 Magnification: 120

Step 2
Name

Start the VBAIDE and create a form with one button Caption ?

CmdTriangle

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 3
Insert a module and enter the code required to show the form

Step 4
Enter the following code for the triangle function

Private Sub CommandButton1_Click() Dim Radius As Double Dim objTriangle As AcadLWPolyline Dim varP(0 To 7) As Double

varP(0) = -86.6 'x coordinate varP(1) = -50 'y

varP(2) = 86.6 'x varP(3) = -50 'y

varP(4) = 0 'x varP(5) = 100 'y

varP(6) = varP(0) 'back to start x varP(7) = varP(1) 'start y

Set objTriangle = ThisDrawing.ModelSpace.AddLightWeightPolyline(varP)

objTriangle.Closed = True objTriangle.Update 'to refresh screen


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

End Sub

Step 5

Save the project and exit the VBAIDE. Using AutoCAD, choose manage load application load The ShowTriangleForm macro should be selected, press run to activate the program.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 10
Add ellipse
As with the polyline and line commands, the ellipse relies on variables to store values such as Center Radius Length etc Then uses .AddEllipse to create the object Step 1 Create a form within the VBAIDE and attach one button. Name the form frmEllipse Step 2
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Insert a module and enter the code required to show the form Step 3 Enter the following code for the ellipse button... Sub cmdEllipse_click() 'draw ellipse Set objEllipse = ThisDrawing.ModelSpace.AddEllipse(varCenter, varMajor, varRatio) objEllipse.Update End Sub Although the above code does eventually draw an ellipse, right now the variables dont have any values assigned to them. What we need to do is make the program automatically set up the variable values as the program is run. Step 4 From within the code window, select the object drop down list (top left of the window) and choose frmEllipse. Select the procedure drop down list (top right) and choose activate. This creates a new function called frmEllipse_Activate() which we can use to set up the values Step 5 Enter the following code into the frmEllipse_Activate function varCenter(0) = 30 center x varCenter(1) = 0 center y varCenter(2) = 0 center z varMajor(0) = 10 varMajor(1) = 0 varMajor(2) = 0 varRatio = 0.5 Now every time the program is run, these values will be stored within the variables. The coding isnt complete yet! Because the variables are being accessed by two different functions, we need to declare them available to the whole program.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Normally they would be declared (using dim) at the beginning of the function, so we will declare them at the beginning of the program (before any functions begin) immediately beneath General Declarations. Step 6 Type the following code below General Declerations Dim varCenter(0 To 2) As Double Dim varMajor(0 To 2) As Double Dim varRatio As Double Dim varStart As Double Dim varEnd As Double Dim objEllipse As AcadEllipse Dim objLayer As AcadLayer Step 7 Save and test the program

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 11a
Looping lines
Sometimes it is not practical to code every object required. In this instance we can use a repeat loop to create one line, reposition its coordinates and redraw it in another location.

Not only is the code easier to follow, it can save hours of coding time (most companies now pay their employees by the amount of modules they produce, not by the hour !)

Step 1
Create a new drawing in AutoCAD

Zoom:

180,85

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Magnification: 250

Step 2
Using the VBAIDE create a form with two buttons and a module to enable macro loading.

Name cmdLines cmdErase

Caption Draw lines Erase all

Step 3

Enter the following code for the lines button... Sub cmdLines_click() Dim lines As AcadLine Dim i As Integer Dim l As Integer Dim w As Integer Dim dist As Integer

Dim p1(0 To 2) As Double Dim p2(0 To 2) As Double

For i = 0 To 300 stop when i = 300 or more p1(0) = i: p1(1) = 0: p1(2) = 0 p2(0) = i: p2(1) = 100: p2(2) = 0

Set lines = ThisDrawing.ModelSpace.AddLine(p1, p2)

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering i = i + 10 Next i End Sub

Do you need to add lines.update?, if so where?

Step 4
Save and run the program to test.

Program 11b

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Looping lines

Sometimes it is not practical to code every object required. In this instance we can use a loop to create one line, reposition its coordinates and redraw it in another location.
Not only is it easier to follow, it can save hours of coding time (most companies now pay their employees by the amount of code they produce, not by the hour)

Step 1

Create a new drawing in AutoCAD

Zoom: Magnification:

180,85 250

Step 2
Using the VBAIDE create a form with two buttons and a module to enable macro loading.

Name cmdLines cmdErase

Caption Draw lines Erase all

Step 3
Enter the following code for the lines button... Sub cmdLines_click() Dim lines As AcadLine Dim i As Integer
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Dim l As Integer Dim w As Integer Dim dist As Integer

dist = 20 l = 360 w = 160

Dim p1(0 To 2) As Double Dim p2(0 To 2) As Double

For i = 0 To l Step (dist) p1(0) = i: p1(1) = 0: p1(2) = 0 p2(0) = i: p2(1) = w: p2(2) = 0 Set lines = ThisDrawing.ModelSpace.AddLine(p1, p2)

Next i

End Sub

Do you need to add lines.update?, if so where?

Step 4
Save and run the program to test.

Step 5
If it works, return to the VBAIDE

Activate the code window for the erase button and enter the following code...
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Public Sub EraseAll()

Dim selSet As AcadSelectionSet Dim Indx As Integer

Set selSet = ThisDrawing.PickfirstSelectionSet

selSet.Clear

ReDim ssobjs(0 To ThisDrawing.ModelSpace.Count - 1)_ As AcadEntity

For Indx = 0 To ThisDrawing.ModelSpace.Count 1_ Set ssobjs(Indx) = ThisDrawing.ModelSpace.Item(Indx) Next

selSet.AddItems ssobjs

selSet.Erase

selSet.Delete

End Sub

Step 6

Now save and run the program again, this time after pressing the draw lines button, press the erase button to clear the screen.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 12
Modularity
Something all good programming languages allow is modularity, this means large complex programs can be constructed from a collection of more manageable short routines (called sub routines) and each called up only when required.

This means writing a sub routine once and using it several times. Saving time writing the code and if it needs changed, only the one routine needs altered.

The biggest advantage however is that sub routines can be used by more than one form, e.g. a quit button on three forms could all share the quit sub routine.

Step 1
Open the lines program from booklet 11 into VBAIDE

Step 2

While in the form design window, delete the erase button.

Step 3

Double click the lines button to enter the code window.

Step 4
Change the beginning line of code from

Sub cmdLines_click() Change to: Sub DrawLines () This change effectively means the code is no longer attached to the button named cmdLines but the code can still be called from another subroutine by simply typing DrawLines
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 5
Change the line:

Sub cmdErase_click()

Change to:

Sub EraseAll() This change effectively means the erase code is no longer attached to a button named cmdErase but the code can still be called from another subroutine by simply typing EraseAll

Step 6
While in the code window, select cmdLines from the object drop down list

This creates a new blank sub routine for the click event of that button

Step 7

To call up another sub routine, we simply type the name of that routine The code for the click event for the lines button is... Eraseall which calls the EraseAll routine wherever it is DrawLines which calls the DrawLines routine wherever it is Type both lines in lowercase, as you press return to access the next line, the interface recognises the functions and changes the lettering to match - Provided we have already programmed these VBA subroutines i.e. EraseAll and DrawLines. This is called Intellisense.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Get the Lines routine from a previous exercise. Here is the code to for the EraseAll routine: Private Sub EraseAll() 'NOTE this erase all routine doesn't work if no objects 'exist

Dim selSet As AcadSelectionSet Dim Indx As Integer

Set selSet = ThisDrawing.PickfirstSelectionSet

selSet.Clear

ReDim ssobjs(0 To ThisDrawing.ModelSpace.Count - 1) As AcadEntity

For Indx = 0 To ThisDrawing.ModelSpace.Count - 1 Set ssobjs(Indx) = ThisDrawing.ModelSpace.Item(Indx) Next

selSet.AddItems ssobjs

selSet.Erase

selSet.Delete ThisDrawing.Application.Update

End Sub

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 13
Intermediate modularity

Normally creating more advanced program means much more typing. This program however will require very little new code. Instead we will copy and paste (lots of) code from programs we have already created to create a modular program.

Step 1

Launch AutoCAD and initiate the VBAIDE

If AutoCAD is already open:

Choose Manage Applications VBA Manager (Or we could just type VBAMAN at the command line).

This will invoke the VBA manager Within this we can load and unload VBA files, initiate the macro manager or access the IDE.

Select any projects within the project window and press unload.

Do this for all the files named before proceeding to the next step

Step 2
Open the VBAIDE and create a new form with six buttons

Name FrmModularity cmdLine

Caption Collection of routines Draw a line

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering cmdRectangle cmdEllipse cmdTriangle cmdErase cmdDraw Rename the project vbaBigOne Draw a rectangle Draw an ellipse Draw a triangle Erase all Draw all shapes

Step 3

Get the code from previous exercises: Line Rectangle Ellipse Triangle EraseAll = = = = = program6 program8 program10 program9 program12

Step 4
Return to the IDE and carefully take a look at the project window. Hopefully you have been changing the project name EACH TIME otherwise it will be hard to make any sense of it.

There should be the following projects loaded:

VbaBigOne VbaRectangle VbaTriangle VbaEllipse vbaLine

Step 5
Select the vbaRectangle project, it should expand to reveal the form.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Double click the form within the project window to display the form.

Step 6
Double click the rectangle command button to activate the code window

Select all the code for the cmdRectangle button and copy it to the clipboard

Step 7

Select the vbaBigOne project and access the code window.

Step 8

Ensure the cursor is outside any sub routines and paste the code held in the clipboard.

Step 9 Change the name from Sub cmdRectangle_click()


Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Change to Sub DrawRectangle() Step 10 Double click all the buttons on the form to create an empty sub routine for each function Step 11 Type the following code in the sub routine for the cmdRectangle button in the vbaBigOne project... DrawRectangle Now when the button is pressed, it initiates the DrawRectangle function instead of executing the code Step 12 Select the vbsEllipse project Step 13 Select the code required to create the ellipse and copy to the clipboard Step 14 Paste it onto the code window of the vbaBigOne project Step 15 Rename the line Sub cmdEllipse_click() Change to Sub DrawEllipse() Access the sub routine for the Draw ellipse button and type the following code... DrawEllipse Again this will initiate the code required instead of executing the actual code Step 16 Carry out the same procedure for all the other buttons on the Modularity form (vbaBigOne) Step 17 Add the following code to the cmdDraw button DrawEllipse DrawLine
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering DrawTriangle DrawRectangle This will invoke all the sub routines, creating ALL the shapes Step 18 Save the program if you havent already Step 19 Run the program pressing each button followed by the Erase button Being able to copy paste from one form to another means (in theory) as a programmer, you will only have to code a function once and just reuse it for every other program where its required.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 13
Clipping raster images

As AutoCAD is a vector based drawing environment, it needs to be able to work differently with raster files. One way of achieving this is to link the raster file through a path name, but like external references (xrefs), not actually insert the image into the drawing file. By attaching images using linked paths, or by using DesignCenter (drag and drop), you can link images to your drawing and only slightly increase the file size of your drawing. Once an image has been attached it can be re-inserted or copied. Each insertion has its own clip boundary and individual settings for brightness, contrast, fade, and transparency.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

To insert a raster file into the drawing, type image (or im for the keyboard shortcut) at the command line. This invokes the image manager, which allows raster files to be; located, attached, reloaded, unloaded, detached and their properties explored.
The same principles are adhered to when using VBA to attach a raster file to the drawing, the link to the file is required as are the insertion point and scale value. Step 1 Add three buttons to a form: Name cmdAddRaster cmdClip cmdErase Caption Add raster Clip Erase

Step 2 Add the following code to the erase button click event objRaster.Delete ThisDrawing.Application.Update Instead of erasing the whole drawing, the above function deletes only the raster file. Step 3 Code the general section of the code window with the following Dim varInsertPoint(0 To 2) As Double Dim objRaster As AcadRasterImage Dim varImgName As String Dim varScaleF As Double Dim varAngle As Double Step 4 Add the following code to the cmdAddRaster button.. Private Sub cmdAddRaster_Click() 'inserts an image into autocad window ' Setup AddRaster End Sub The above button calls two sub routines which need to be coded Step 5 Sub Setup() varImgName = "C:/RasterFile.jpg" varInsertPoint(0) = 0x
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering varInsertPoint(1) = 0y varInsertPoint(2) = 0z varScaleF = 1 full size varAngle = 0 End Sub Step 6 Now code the AddRaster function to insert the image Sub AddRaster() On Error GoTo ErrMsg Set objRaster =_ ThisDrawing.ModelSpace.AddRaster(varImgName,_ varInsertPoint, varScaleF, varAngle) objRaster.Update ' update here Exit Sub 'this ends the program if all is well ErrMsg: 'otherwise show error message MsgBox varImgName & " not found." End Sub This sub routine contains a simple error trap that informs the user when the image isnt found.

Step 7 The clip button has to setup an array of points, containing the clip coordinates, in this case a star shape... Private Sub cmdClip_Click() Dim objRectangle As AcadLWPolyline Dim varPoint(0 To 21) As Double varPoint(0) = 0.47 'split user defined point 1 into x, y varPoint(1) = 0 varPoint(2) = 0.6 varPoint(3) = 0.35 varPoint(4) = 0.98 varPoint(5) = 0.35 varPoint(6) = 0.68
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering varPoint(7) = 0.56 varPoint(8) = 0.8 varPoint(9) = 0.9 varPoint(10) = 0.5 varPoint(11) = 0.7 varPoint(12) = 0.2 varPoint(13) = 0.9 varPoint(14) = 0.3 varPoint(15) = 0.56 varPoint(16) = 0.02 varPoint(17) = 0.35 varPoint(18) = 0.39 varPoint(19) = 0.35 varPoint(20) = 0.47 'back to beginning varPoint(21) = 0 'must be done or it doesn't work Set objRectangle =_ ThisDrawing.ModelSpace.AddLightWeightPolyline(varPoint) objRectangle.Closed = True objRectangle.Update objRaster.ClipBoundary (varPoint) objRaster.Update End Sub Step 8 Although the program will work at this stage, we havent given the form a start coordinate. Add the following code to the form load event UserForm1.Left = 50 UserForm1.top = 200 CAD users BEWARE, this will activate the form 50 pixels from the left, and 200 pixels from the TOP. Unlike AutoCAD the origin (0,0) is located at the top left corner of the screen, positive X will still mean east, however positive Y is in the direction of south. Step 9 Save the program (is this the first time you have saved this program?)
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering Run using the load and macro menu to test whether the program is robust and fit for purpose. Have you remembered to add the module? (ShowClipForm)

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Program 14
Translating raster images

As with the earlier translation examples (2D primitives), the move command would not give a complete understanding of how AutoCAD actually translates objects around the screen. Imagine creating a closed polyline shape using the following absolute coordinates: P1 P2 P3 P4 50,50 100,50 100,100 50,100

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering By moving the shape 50mm in the direction of the X axis, all the points have to be recalculated by adding 50 to the X values. If the shape were created using relative coordinates, only the insertion point would require re-calculating as all the other points would still be relative to this. By manipulating the insertion point of the raster image, the image can appear to translate across the screen as it is updated. Step 1 Create the following form and attach the buttons using your discretion for the names (USE VBA prefixes)

Step 2 Copy and paste the code from the previous exercise for the cmdAddRaster button (from the clip raster example) Step 3 To pan the drawing using the cmdPanUp button the following code is used..

EraseLast varInsertPoint(0) = varInsertPoint(0) varInsertPoint(1) = varInsertPoint(1) + 1 varInsertPoint(2) = varInsertPoint(2) AddRaster The EraseLast function is called to clear the existing image from the screen, otherwise the image would appear to be copied across the screen. The insertion point has to be re-calculated before calling the AddRaster function to re-create the image in the new location. As this button is only concerned with panning the image upwards, the Y coordinate (varInsertPoint(1)) has to increase, while the X and Y retain their values.
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering This is achieved by using the sum value = value + 1 For instance if the current Y value is 5... Y=5+1 Or Y=6 Every time the Pan up button is pressed the following operation is carried out Erase the raster image Move the insertion point one millimetre in the direction of the Y axis Re-insert the image file in the new location

Step 4 The following button allowed the image to be translated in the direction of positive Y, what if it were to be translated using the negative? Below is the code fro the cmdPanLeft button... EraseLast varInsertPoint(0) = varInsertPoint(0) - 1 varInsertPoint(1) = varInsertPoint(1) varInsertPoint(2) = varInsertPoint(2) AddRaster Again the first line calls the erase function, however this time its the X value (varInsertPoint(0)) which is to be altered. Using the following sum we can re-calculate the insertion point of the image Value = value - 1 For instance if the current X value is 10... X = 10 - 1 Or X=9 Use the skills you have learned to code the remaining two buttons.

Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Raster booklet 3

Using KeyCode

The previous program explained the method behind translating objects about the AutoCAD screen. This next tutorial will allow that method to be applied to keystrokes. Manipulating objects using keystrokes is nothing new, computer games have allowed the user to control a game using the keyboard for many years, however I
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering have never came across another program which allowed the user to translate an object across the AutoCAD screen directly by pressing the arrow keys. The logic behind it is quit simple, a command button has its KeyDown event activated. The code is triggered when a button is pressed on the keyboard that corresponds with a predetermined code e.g. vbKeyUp = the up arrow key runs the PanUp sub routine. Step 1 Create the following form with correctly named buttons and project

fig 1 KeyCode form Step 2 Declare the following variables in the general section of the code window... Option Explicit Dim varInsertPoint(0 To 2) As Double Dim objRaster As AcadRasterImage Dim varImgName As String Dim varScaleF As Double Dim varAngle As Double Step 3 Remembering to use comments, add the following code to the cmdAddRaster button Setup AddRaster cmdAddRaster.Caption = "Use the arrow keys"

Step 4 Before adding the code for this button, ensure the raster file (get it here) is located on the C:/ drive and named correctly: RasterFile.jpg varImgName = "C:/RasterFile.jpg" varInsertPoint(0) = 0 varInsertPoint(1) = 0
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering varInsertPoint(2) = 0 varScaleF = 1 varAngle = 0 Step 5 Now code the AddRaster sub routine On Error GoTo ErrMsg Set objRaster = ThisDrawing.ModelSpace.AddRaster(varImgName,_ varInsertPoint, varScaleF, varAngle) objRaster.Update 'put update here Exit Sub 'this ends the program if all is well ErrMsg: 'otherwise show error message MsgBox varImgName & " not found." Step 6 To allow the keystrokes to be recognised, a KeyDown event must be coded, this is similar to the object_Click() events used previously, however responds to all predetermined keyboard/ mouse keys. The KeyDown event needs to be attached to the active object (e.g button or form etc), and as the current object will be the amdAddRaster button we will code this event. Place the cursor in the cmdAddRaster_Click() section of the code window, then using the procedure drop down window, select the KeyDown procedure. Add the following code to this procedure

If KeyCode = vbKeyUp Then PanUp ElseIf KeyCode = vbKeyDown Then PanDown ElseIf KeyCode = vbKeyLeft Then PanLeft ElseIf KeyCode = vbKeyRight Then
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering PanRight Else 'do nothing for any other key End If Looking at the above program, you should be able to spot the lines of code that are simply calling other sub routines to limit the lines of code we need to type. PanUp PanDown PanLeft PanRight

It also makes use of VBAs ability to access operating system functionality VbKeyUp VbKeyDown VbKeyLeft VbKeyRight VbKeyF1 VbKeyNumpad1 VbKeyA Up arrow key Down arrow key Left arrow key Right arrow key F1 key 1 key (number pad) A key

Step 7 The PanUp sub routine can be coded with the following... EraseLast varInsertPoint(0) = varInsertPoint(0) varInsertPoint(1) = varInsertPoint(1) + 1 varInsertPoint(2) = varInsertPoint(2) AddRaster The previous exercise demonstrated the method behind the above calculation, however this time it has been initiated by pressing the up arrow key. Step 8 Code the PanLeft sub routine with the following code... EraseLast varInsertPoint(0) = varInsertPoint(0) - 1 varInsertPoint(1) = varInsertPoint(1) varInsertPoint(2) = varInsertPoint(2) AddRaster
Board of Management of Motherwell College: Registered Charity Number SC021206

Department of Engineering

Step 9 Code the remaining two keycode events using the skills you have learned. Step 10 Code the EraseLast sub routine to complete the program Step 11 Save and run the program to test.

Board of Management of Motherwell College: Registered Charity Number SC021206

You might also like