The Amazing FILLET Zero Command

So you’re drawing away, and you’ve got two lines that need to come together to form a corner, but at the moment the lines are too short or too long. Instead of extending or trimming them, it can be quite neat to use the FILLET command with a radius of 0.

For those of you that already knew this little tip but dodged it in the past because you have to mess around making sure your fillet radius was 0, you’re in luck because you don’t actually have to explicitly set the fillet radius to 0 at all. In a similar fashion to the TRIM and EXTEND commands, you can hold down the SHIFT key to modify the behaviour of this command. As you guessed, holding down the SHIFT key during the FILLET or CHAMFER commands will force a 0 radius or chamfer.

One final note, if you’re doing this with just lines, you’ll be left with what you started with – lines. However, if either one or both of the entities are in fact polylines, they will be joined to form a single polyline. If you planned to join them afterwards this can be useful to know.

The LENGTHEN Command

LENGTHEN is the older, much more specialised brother of the EXTEND command. Although EXTEND was always the more popular of two line-elongating siblings, he always felt somewhat shadowed by his more talented and feature rich, yet understated brother…

I could probably keep up this metaphor for the entire post, and whilst part of me wants to for pure comedy value, I feel it may detract from the usefulness of the post… So what I’m saying is the LENGTHEN command is very useful in specific situations, but in my experience isn’t very widely known or used.

As an example, say you’ve got a polyline that represents a wire going through a complex pulley arrangement. You know the route of the wire, you know how long the wire is supposed to be, but how on earth do you draw your polyline to an exact length through an irregular path? Yes, you could use the MEASURE command, but for me that is a bit inelegant for what we’re trying to do. The best way is to use the LENGTHEN command.

So, draw your line through the pulley arrangement, don’t worry about what the total length is for now, just make sure it follows the path you want. Now invoke the LENGTHEN command. In the LENGTHEN command there is the option to specify the total length – press T to select this option, and then enter the desired length. Then, you can select the line that represents your wire, and this will be extended or trimmed to the length you specified. Make sure you pick end of the line, or it will extend or trim from the wrong end. That’s it, thought I do quite like the irony of the LENGTHEN command potentially making the line shorter…

Finally, and as with all my posts, I’d like to suggest that you pop your email address in below. You’ll receive regular updates of what I’ve been adding to this blog, and I’m always going to be adding new content regularly. If you have any questions please do not hesitate to post comments – I will always be willing to answer questions.

Trim outside boundary with the EXTRIM command

Many thanks to Dave Murchison for finding the EXTRIM command, and sharing it with me. This command is basically an extension to the TRIM command. With this command you can select a boundary to trim back all objects to. This is great for clipping back construction lines etc back to the limits of whatever it is you’re drawing. Bear EXTRIM in mind in future as it clearly has great potential for saving a lot of time.

Will

The TRIM and EXTEND commands

I group the TRIM and EXTEND commands together because they’re basically equal and opposite. They are typically used quite commonly when drawing, but there are a few little tips for using them that can be really handy to know.

Basic Usage

Invoke the TRIM command. AutoCAD® then prompts you for a selection. A lot of people simply ignore this step and just use the default option to select all, but I tend to avoid doing this in nearly all cases. My reason for this is because you’re making AutoCAD® work harder if you select all. When you subsequently click an object to trim, AutoCAD® has to perform an intersection check with every single entity you selected, for each of the entities you selected to trim. So if you’ve got 10,000 entities in modelspace, and you selected to trim 50 lines, you’re asking AutoCAD® to perform 50 * 10,000 = 1 million comparisons. If AutoCAD® starts to hang and crashes, I wouldn’t place the blame entirely on AutoCAD…

 On the other hand, if you’d taken the time to select the entity you want to trim back to, you’re only asking AutoCAD® to perform 1 * 50 = 50 comparisons, which is drastically less than before. Get in the habit of doing this and you’ll avoid a lot of AutoCAD® hanging and possibly crashing.

What about the EXTEND command?

This is perhaps one of the most useful “quick tips” I’ve come across. I recommend that you do this right now – go into the CUI editor and remove the EXTEND command completely from your toolbars as you will never need to use it again. During the TRIM command, press and hold the SHIFT key to switch to extend m0de. That way you can tidy up all your loose ends without having to switch between the two commands.

Other Information

There also exists a LENGTHEN command, which you’d think to be very similar to the EXTEND command. You’d be right – the commands are very similar, but the LENGTHEN command has some very useful differences which make it worthy of a post of its own.

If you found this post useful, I’d like to encourage you to subscribe below. I will be posting tips like this all the time – there are so many useful tweaks that you’d never know unless someone told you. Let me tell you more!

AutoCAD® and Excel – a match made in heaven?

There are many ways to input commands into AutoCAD®. You will be familiar with the command line as the main method for driving AutoCAD®, any you will most likely know that toolbars are usually just shortcuts to commands that are in fact sent to the command line. Understanding how AutoCAD® accepts input from the command line allows us to invent our own ways of inputting data, and one of the most useful ways is to copy and paste commands directly into the command line.

Copy and paste this list of commands into the command line:

LINE 0,0 30,45
LINE 30,45 60,77.9422863405995
LINE 60,77.9422863405995 90,90
LINE 90,90 120,77.9422863405995
LINE 120,77.9422863405995 150,45
LINE 150,45 180,1.10263360941776E-14
LINE 180,1.10263360941776E-14 210,-45
LINE 210,-45 240,-77.9422863405995
LINE 240,-77.9422863405995 270,-90
LINE 270,-90 300,-77.9422863405995
LINE 300,-77.9422863405995 330,-45
LINE 330,-45 360,-2.20526721883552E-14  

You should now have a rather coarse looking sine wave which was drawn by a series of LINE commands. “What’s the point of that” you say? Well the drawing of a sine wave is just an arbitrary example of copy and pasting commands directly into the command line. Where this concept really comes into it’s own is when we use Excel to create the list that we copy. Here’s how I created the list above:

The method for creating the coordinates is unimportant – what you should focus on is the formula for creating the command:

="LINE " & E3 & "," & F3 & " " & E4 & "," & F4 & " "

Using a bit of concatenation of cells with the ‘&’ operator, we can make the content of cells represent a command in AutoCAD®, which we can then later copy and paste into AutoCAD®. Taking this further you can string a few commands together for each row of data, allowing you to achieve more complex tasks than drawing a simple line.  So if you had a few coordinates for say manhole locations, and each had an associated ID number, you could quite easily create a formula to firstly input a circle at the correct location, and then insert some text at the same location with the ID number. If you have a block, use the INSERT command in your formula instead. The possibilities are endless. I’ll never forget the time that I had to produce a tree survey based on a huge list of coordinates and other information in Excel. We’d budgeted for a fair amount of work, but with a bit of knowhow it was as easy as copy and paste.

I hope you found this tip useful, and if you did I would like to recommend you subscribe below. I’ve got loads more tips to share!

Command Aliases in AutoCAD® with acad.pgp

Thought I’d share something that I did a while back which turned out to be a really good move, though it may not be for everyone. The rationale behind this exercise is to make commonly used commands more at the fingertips of the user, and thus improve productivity.

I have set up a range of one and two letter command aliases that can be entered solely with the left hand using various combinations of the keys normally associated with touch typing with the left hand. I can now use my pointing device with one hand, and invoke up to 240 commands with the other.

This is arguably faster than clicking a toolbar icon, but this is not the only benefit. The user benefits from more screen space if they choose to remove toolbars they no longer need. More significantly, the user can interact with the PC without taking their eyes off the screen to type (or locate their right hand correctly to type), and can zoom/pan & analyse and think about the drawing WHILST entering commands.

It does come at a cost though, because you have to remember all the keybinds! To combat this, it helps to have some logic behind how they’re laid out – for instance I have my keybinds laid out as follows:

Commands beginning with A draw things, commands beginning with S modify things, commands beginning with D have to do with dimensioning/annotating, and commands beginning with F are miscellaneous. Notice that the first letter of each command resides on one of the keys your fingers should naturally rest upon when touch typing. Also, the commands are organised from left to right in order of when they would normally be used when constructing a drawing: Draw things, Modify them, Dim them up then Anything else.

Again to assist with remembering commands, I’ve tried to assign a second letter that corresponds well to the command itself. For example, AC is the CIRCLE command, AR is the RECTANG command, AS is the SPLINE command, SA is the ARRAY command, SF is the FILLET command, DR is the DIMRADIUS command, DS is the DIMSTYLE command etc… You get the idea.

Finally, commands that are very frequently used such as line, polyline, move and copy can be assigned to a single keystroke. For example, I’ve set A to LINE, S to MOVE and D to DIMLINEAR.

Having used this input method for quite a while now I can certainly say I like it. I currently have ZERO toolbars on my screen, and I can invoke any command I need from my left hand within about half a second. Once you’ve got used to it you instinctively know how to drive CAD – you can focus your energy on keeping your mind focussed on what you’re doing, and you need not be distracted by moving your mouse over to toolbars etc… It might sound trivial but keeping your eye on what you’re doing is helpful. You can snap your mouse to the right spot while you input the command.

Here’s my list of keybinds:


;GENERATED_KEYBINDS
;Anything entered beyond this point will be DELETED upon the next automatic update.
;Please input your own customisations BEFORE the GENERATED_KEYBINDS tag.
;Defined KeyBinds
AE, *ELLIPSE
AR, *RECTANG
AT, *MTEXT
ATT, *TEXT
AA, *LINE
AS, *SPLINE
AD, *HATCH
AF, *INSERT
AZ, *RAY
AX, *XLINE
AC, *CIRCLE
AV, *-VPORTS
AB, *BLOCK
SW, *OFFSET
SE, *MIRROR
SR, *ROTATE
ST, *TRIM
SY, *LENGTHEN
SA, *ARRAY
SS, *COPY
SD, *BLOCK
SF, *FILLET
SG, *CHAMFER
SZ, *PEDIT
SX, *EXPLODE
SC, *CHSPACE
SV, *STRETCH
SB, *SCALE
DQ, *QLEADER
DW, *DIMJOGLINE
DE, *DIMDIAMETER
DR, *DIMRADIUS
DT, *MLEADERALIGN
DA, *DIMANGULAR
DS, *DIMSTYLE
DD, *MLEADER
DDS, *MLEADERSTYLE
DF, *DIMALIGNED
DZ, *UNITS
DX, *MLEADEREDIT
DC, *DIMCONTINUE
Q, *QSAVE
E, *ERASE
R, *REGEN
A, *PLINE
S, *MOVE
D, *DIMLINEAR
F, *LAYER
\, *PSPACE
Z, *U
X, *XATTACH
V, *VBAMAN
FE, *PURGE
FT, *ALLON
FA, *LAYISO
FS, *LAYUNISO
FD, *LAYFRZ
FF, *MATCHPROP
FG, *LAYMRG
FC, *LAYMCUR
QQ, *SAVEAS
QW, *CLOSE
QE, *SAVEALL
QR, *CLOSEALL
QA, *QNEW
RE, *REVUP
RR, *REGENALL
RC, *REVCLOUD
K, "\\SWIN-FS-01\water\wh\CAD\CAD UTILITIES\Macros\keys3.dwg", 1,,
XX, *IMAGEATTACH
XC, *XCLIP
VR, *VBARUN
VA, *VBAIDE
C, *COPYCLIP
CA, *AI_SELALL
CX, *CUTCLIP
CC, *COPYBASE
CV, *PASTECLIP
CB, *PASTEORIG
PP, *PLOTPDF
PD, *PLOTDWF

One final thing, I’ve created a script embedded into a dwg file that automatically updates the acad.pgp file with keybinds. In the dwg are some QWERTY style keyboards so that you can visualise your keybind layout. Within this dwg file you can simply edit the text on each key to set what command it is associated with. Then, you can just save the drawing file and it will add the keybinds to the end of your acad.pgp file. Download the file here:

keybinds

To use this file, simply copy it to the same directory as your acad.pgp, open the .dwg and edit to suit.

If you found this post useful, please do subscribe below. I have many tips to share, and you’ve nothing to lose!

Introduction to VB.NET in AutoCAD

VBA is in the process of being phased out, and the replacement is .NET. This may disappoint some of you that have VBA applications/skills, but you will be pleased to hear that you can still use code that you have, and all you know about VBA programming with AutoCAD® can still be put to good use using VB.NET. The following tutorial sets the foundation for creating your first VB.NET project, and should serve as a good starting point for migrating your code across to VB.NET.

What you need

There is no native IDE (integrated development environment) within AutoCAD® for developing .NET projects like you could with VBA (via the command VBAIDE). Instead, you need an external software development package for writing and compiling your code. Fear not however, you can download express editions of several programming suites for free directly from Microsoft’s website. Click here to visit the page for downloading Visual Basic Express 2010.
Next, you need to download the ObjectARX programming interface from AutoDesk’s website. Click here to visit the page for downloading ObjectARX. Ensure you acquire the correct version of the ObjectARX libraries for your version of AutoCAD.

Create your first VB.NET AutoCAD® project

Open Microsoft Visual Basic Express, and select “New Project”, and then select the “Class Library” option. This creates a project that compiles to a dynamic link library (.dll file). In VBA you automatically have access to the AutoCAD® object, including objects such as ThisDrawing, but in this environment we have to create references to AutoCAD® explicitly ourselves. We do this by naming a reference to ObjectARX, which contains the AutoCAD® type libraries that we want to use.

  1. Under the Solution Explorer window, right click on your project (ClassLibrary1 if you haven’t renamed it), and select Properties.
  2. Click on the References Tab.
  3. Click on the Add dropdown, and select Reference.
  4. Click on the Browse Tab, and navigate to where the ObjectARX libraries are installed. Typically this will be C:\ObjectARX 2011\
  5. Depending on your preference, open the folder inc-win32 or inc-x64.
  6. Select the dll files Autodesk.AutoCAD.Interop.dll and Autodesk.AutoCAD.Interop.Common.dll, and click OK. This imports the AutoCAD® type libraries.
  7. Add another reference, and this time select the inc folder. Select AcMgd.dll and AcDbMgd.dll, and click OK. I’m not completely sure why these are required, but apparently they are!
  8. Finally, you’ll notice on the References Tab that the Copy Local property of the AcMgd.dll and AcDbMgd.dll references is set to True. This needs to be False so select them, and under the properties window change the Copy Local property to False.

Writing some initial code

Our project is now set up with all the references required to link to AutoCAD®. Now we can begin writing code.
Switch back to code view (If you haven’t renamed anything, double click on Class1.vb under Solution Explorer). We need to specify in this class which libraries from our references we intend to use, so right at the top of the class (before Public Class Class1) put the following code:

    'Contains the AutoCAD® Type Library
    Imports Autodesk.AutoCAD.Interop
    'Contains the AutoCAD/ObjectDBX Type Library
    Imports Autodesk.AutoCAD.Interop.Common

Now in VBA, we had access to the ThisDrawing object. This is quite useful, so it would be useful to have the same functionality here. Now that we have access to the AutoCAD® object model, we can add a simple Get procedure to retrieve the object we want. Put the following code inside the Class (between Public Class Class1 and End Class):


    Public ReadOnly Property ThisDrawing As AcadDocument
        Get
            Return Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.AcadDocument
        End Get
    End Property

Now we can use ThisDrawing anywhere within the class as we could in VBA.

Writing our first AutoCAD® Function

Everything is in place now to start producing our own AutoCAD® commands. If you have any VBA code you want to transfer across, you should now be able to paste them into this class. Here’s one that I wrote recently as an example. The code adds a border to MTEXT, and the only difference between this code and VBA code is that I’ve made use of the .NET Try/Catch statement, which is better for error trapping than previous methods in VBA:

    Public Sub CreateMTextBorder()
        Dim ent As AcadEntity
        Dim pnt As Object
        Try
            ThisDrawing.Utility.GetEntity(ent, pnt, "Pick MTEXT to add a border to")
            Dim mt As AcadMText
            mt = ent
            Dim Min As Object, Max As Object
            Dim Coords(7) As Double
            mt.GetBoundingBox(Min, Max)
            Coords(0) = Min(0) - 1
            Coords(1) = Min(1) - 1
            Coords(2) = Max(0) + 1
            Coords(3) = Min(1) - 1
            Coords(4) = Max(0) + 1
            Coords(5) = Max(1) + 1
            Coords(6) = Min(0) - 1
            Coords(7) = Max(1) + 1
            If ThisDrawing.ActiveSpace = AcActiveSpace.acModelSpace Then
                ThisDrawing.ModelSpace.AddLightWeightPolyline(Coords).Closed = True
            Else
                ThisDrawing.PaperSpace.AddLightWeightPolyline(Coords).Closed = True
            End If
        Catch
            ThisDrawing.Utility.Prompt("Invalid Selection")
        End Try
    End Sub

Make sure that your subroutine is declared Public as opposed to Private, so that it will be visible by AutoCAD®. Also, there is one final piece of code we need to add to make this visible by AutoCAD®. We need to add some META data before the subroutine, which tells AutoCAD® that the subroutine is callable directly from AutoCAD®. This is where we assign our subroutine a Command Name for our AutoCAD® Command Line. Add the following code on the line before Public Sub CreateMTextBorder():

	<Autodesk.AutoCAD.Runtime.CommandMethod("MTEXTB")> _

Whatever we put in the brackets will be the command that we type into the AutoCAD® command line.

Our class is now complete, and is ready to be compiled into a DLL file for use with AutoCAD.

Compiling

Under the debug menu, we can select Build to create our .dll, but if we do it now the NETLOAD command in AutoCAD® will fail to load the .dll file. This is because the .dll file must be built on the same version of the .NET framework as the version of AutoCAD® you are using. AutoCAD® 2011 is built on version 3.5 of the .NET framework, so we need to tell VB to compile our class using this version.

  1. Go to project properties as we did before for adding references.
  2. Click on the Compile Tab.
  3. At the bottom, click on Advanced Compile Options.
  4. At the bottom of the Advance Compiler Settings dialog box, select the Target Framework .NET Framework 3.5.
  5. Click OK. This usually requires closing and reopening the project afterwards.

Now we can build our .dll file based on the same .NET Framework as AutoCAD®, which should make it compatable. It is useful to have the Output Window open, so that we can grab the location of the compiled .dll file once the build is complete. You can open this window by going Debug > Windows > Output. Go Debug > Build, and this will compile the .dll file. Copy the path of the .dll file from the Output window, and open AutoCAD.

Type NETLOAD into the command line. This is the command for loading .NET projects. You will be prompted to supply a path, so paste in the path to the .dll file we just created. If it worked, it should silently finish the command, i.e., you shouldn’t get any error messages. Now that the .dll is loaded you should be able to type in the command specified in the META data to call the subroutine inside the .dll, in the case if this example, MTEXTB.


I would like to take this opporunity to suggest that you subscribe to my blog – if you work with AutoCAD® I have many tips and tricks on the tip of my tongue. I guaranteee that you will find it a valuable resource.

VBA in AutoCAD® – Tutorial 2: Subroutines

Introduction

This tutorial assumes that you have read all previous tutorials, but have no other VBA knowledge for AutoCAD® or otherwise.

In this tutorial, I will explain the basics of subroutines.

Subroutines

In the last tutorial, I explained some basic code. The observant of you will have noticed that there were a few parts of the code that I left unexplained:


Sub QuickExample()
End Sub

This is a subroutine. The first line defines the beginning, and the second line defines the end. Similarly to variables (remember those from the last tutorial?), the name can be changed to whatever we like (certain rules apply). However, the subroutine name must end with a pair of parantheses. If they are omitted, they will be added automatically. You may notice after typing a line such as Sub QuickExample and pressing enter, that the End Sub statement is automatically inserted. If any subroutine has no corresponding End Sub, it will not run, and an error will occur.

A subroutine is a container for our code. If we had a subroutine that contains code that converts TEXT to MTEXT, it would be logical to call it something like ConvertText2MText. When we use the command VBARUN from AutoCAD®, we are presented with a dialog box that gives us the option to execute whatever subroutine we like. So in this example, we would pick the option that refers to the ConvertText2MText subroutine.

The above method using VBARUN is how to execute a subroutine directly from AutoCAD®. We can also run the subroutine from within VBA – perhaps from another subroutine. The way to do that, is to write the subroutine name in our code. So to run the subroutine in the example above, we would simply write:

ConvertText2MText

When VB reaches this line of code, it will jump to the line of code that says Sub ConvertText2Mtext(). Then, it will run the content, and when it reaches the End Sub statement, VB will return to where it was originally, and continue to process code as normal. This can be a useful way of splitting up our VBA applications into logical and understandable chunks that can be called upon whenever necessary.

So lets expand on our example. Lets say that we have 4 subroutines. I’ll put 3 of them below:


Sub ConvertText2MText()
    MsgBox "Convert Text to MText"
End Sub

Sub ConvertLines2Polylines()
    MsgBox "Convert lines to polylines"
End Sub

Sub SetupSystemVariables()
    MsgBox "Do setting up of system variables"
End Sub

I’ve omitted the actual code for these subroutines as it isn’t what I’m focusing on. Each of the above could be called directly from AutoCAD® by entering VBARUN into the command line, and then selecting the desired subroutine to run. But if we actually want to run all of them however, it might be useful to set up another subroutine to call them all:


Sub ReformatDrawing()
    MsgBox "Beginning running all subroutines..."
    ConvertText2MText
    ConvertLines2Polylines
    SetupSystemVariables
    MsgBox "Completed!"
End Sub

When you execute the ReformatDrawing subroutine, it will run the other 3 subroutines in the order that they appear. Some of you might say “You could just put all of the code into one subroutine – why not just do that?”. Well yes you could, but when you start making complicated code its not advisable because it makes it hard to follow. Also, programming in this way makes your code nicely reusable because it easy to transfer whole subroutines from one project to another.

More on Subroutines

We’ve covered the purpose, and basic usage of subroutines. Now I will show you what else subroutines can be useful for.

It is sometimes useful for the subroutine to do certain things based on given input. Say for example we wanted a subroutine that inserts some text into the drawing at a changable position. We can make it so that we can give the subroutine some parameters, and make it do things based on the information we provide. In this example, we could make it so that the subroutine will put text into our drawing based on coordinates that we supply. So I will explain how to pass parameters to a subroutine. Here we have a subroutine that inserts text into our drawing (it’s the same as the one in Tutoral 1):


Sub InsertText()

    Dim MyString As String 'Create string variable
    MyString = "Hello! This is the contents of the string variable called MyString" 'set it to something
    MsgBox MyString 'show it in a messagebox

    Dim Point(2) As Double 'This is how to create an array
    Point(0) = 10 'This is x
    Point(1) = 20 'This is y
    Point(2) = 0 'This is z

    Dim TextHeight as double 'Create double precision floating point number variable
    TextHeight = 10 'set textheight to 10

    ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight  'Add text to drawing in modelspace

End Sub

This subroutine is fine, but it’s not very useful because it does the same thing every time! However, if we alter the code slightly, we can make it a bit more intuative. We can alter the subroutine so that it is anticipating additional information. If we do this, we will have to provide the additional information when we call it. To make the subroutine expect additional information, we add contents to the parantheses as follows:


Sub InsertText(MyString as String)

    MsgBox MyString 'show whatever was passed to the subroutine in a messagebox

    Dim Point(2) As Double 'This is how to create an array
    Point(0) = 10 'This is x
    Point(1) = 20 'This is y
    Point(2) = 0 'This is z

    Dim TextHeight as double 'Create double precision floating point number variable
    TextHeight = 10 'set textheight to 10

    ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight  'Add text to drawing in modelspace

End Sub

Now, to call this subroutine we would use something like:
InsertText “Hello! This is some text that I am passing to the subroutine”

This would need to be contained in another subroutine. I’ll rewrite it all so that it makes some sense:


Sub MainSubroutine
    InsertText "Hello! This is some text that I am passing to the subroutine"
End Sub

Sub InsertText(MyString as String)

    MsgBox MyString 'show whatever was passed to the subroutine in a messagebox

    Dim Point(2) As Double 'This is how to create an array
    Point(0) = 10 'This is x
    Point(1) = 20 'This is y
    Point(2) = 0 'This is z

    Dim TextHeight as double 'Create double precision floating point number variable
    TextHeight = 10 'set textheight to 10

    ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight  'Add text to drawing in modelspace

End Sub

If we input VBARUN into the command line, and select MainSubroutine, we should get exactly the same scenario as we did to begin with. However, it happens differently. This time, we are running the subroutine called MainSubroutine, this is in turn calling the subroutine InsertText, and is providing that subroutine with some text. When VB jumps to the InsertText subroutine, it creates a variable called MyString, and automatically stores the text in here. Notice that I have removed some of the code inside the new sub – it no longer needs to create the MyString variable (with the Dim statement), or set the text in that variable, because it now happens automatically as part of the call to the subroutine.

This is a simple example using one parameter. At the moment this doesn’t really add any more functionality, but we can add more parameters as follows:


Sub MainSubroutine
    InsertText "This is the first call to the InsertText Sub", 10, 20, 0, 10
    InsertText "This is call number 2!", 10, 40, 0, 10
    InsertText "This is the third and final call", 10, 60, 0, 10
End Sub

Sub InsertText(MyString as String, XCoordinate as Double, YCoordinate as Double, ZCoordinate as Double, TextHeight as Double)

    Dim Point(2) As Double 'This is how to create an array
    Point(0) = XCoordinate 'Set the contents of Point(0) to whatever is stored in the variable XCoordinate
    Point(1) = YCoordinate 'Set the contents of Point(1) to whatever is stored in the variable YCoordinate
    Point(2) = ZCoordinate 'Set the contents of Point(2) to whatever is stored in the variable ZCoordinate

    ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight  'Add text to drawing in modelspace

End Sub

Now we’ve set up the InsertText subroutine so that it accepts parameters for the contents of the text, the location, and height. This is more useful from a programming point of view because we can now insert some text into the drawing at any position, any height, and containing whatever contents we like; all only using one line of code as shown in the MainSubroutine.


If you found this useful, please do subscribe to my blog – I’ll always be adding something useful!

VBA in AutoCAD® – Tutorial 1: Introduction

Introduction

Knowing a little bit of programming can be extremely useful in the AutoCAD® environment. Before you cringe with dread at the prospect of having to learn a programming language, it sounds far more difficult than it really is. Especially since VB stands for “Visual Basic” – there’s a clue in the name… Writing simple applications for automating tasks isn’t hard – really.

This tutorial assumes no previous knowledge of VBA in AutoCAD® or otherwise. I will explain the very basics of using VBA in AutoCAD®. I will give a brief overview of the VBA IDE (Integrated Development Environment) and I will explain a small snippet of code and how it works.

What is VBA?

If I assume you know nothing about VBA, it follows that you probably don’t know what VBA stands for. VBA stands for Visual Basic for Applications. Most people reading this will probably have heard of Visual Basic, and are aware that it is a Microsoft Windows based programming language. The “for Applications” bit means that it is integrated behind the scenes in the software application you’re using, be it Word, Excel, or in our case AutoCAD.

Step One – Familiarise with the IDE

In order to begin, we need to access the VBA IDE. This is where we will be working. Input VBAIDE into the command line. This opens up a new window which is the VBA IDE. You should have something that looks like the below:

The section of the screen with the big red “1” is the project window. This shows you all the sections of your VBA project. Right click in this area and select insert/module. This will (surprisingly!) insert a module. A module is basically a container for your code. If you like, you can rename the module from “Module1” to something more descriptive of what the module does or is for.

The section of the screen represented by the number 2 is the properties window. Various aspects of your project have certain properties that can be edited. I won’t go into this right now.

The section of the screen represented by the number 3 is the editing window. If it’s grey at the moment (like in the example), you’re not editing anything. If you’ve added a module, chances are you’re looking at a white screen, and you can type stuff. When you add a module, it automatically opens it up in the editing portion of the screen.

The section of the screen represented by the number 4 is a toolbar – in particular the buttons that handle the execution of code. The run button causes VBA to start executing code from the current subroutine (i.e. the subroutine in the module you’re editing that contains the cursor). The pause button will pause execution, and take you to the debugging screen. The current position that VBA has got to will be highlighted with yellow. The stop button halts execution.

Step Two – Add some code, and run it

Make sure you’re at a state where you are editing a module. You might have at the top of the screen the words “Option Explicit”. This is fine, but also don’t worry if it’s not there. You don’t really need to know about this right now. Paste the following code into the module:

Sub QuickExample()
    Dim MyString As String 'Create string variable
    MyString = "Hello! This is the contents of the string variable called MyString" 'set it to something
    MsgBox MyString 'show it in a messagebox
    Dim Point(2) As Double 'This is how to create an array
    Point(0) = 10 'This is x
    Point(1) = 20 'This is y
    Point(2) = 0 'This is z
    Dim TextHeight as double 'Create double precision floating point number variable
    TextHeight = 10 'set textheight to 10
    ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight 'Add text to drawing in modelspace
End Sub

Everything should have pasted in nicely. The text should automatically change into a lovely assortment of black, dark blue, and green colours. If you get any red, then something went wrong when you copy and pasted. When editing code, different colours of text represent different things. Green text represents a comment or note – this text can be anything and is for the purpose of you making your own notes. Dark blue text represents key words that VB understands. Red text indicates anything that contains errors, or the structure of what you’ve written is wrong. However, just because it’s not red, doesn’t necessarily mean that it contains no errors. Black is anything that doesn’t fall under any of the above.

You probably guessed that to execute the code, you click the run button in the toolbar at the top. The shortcut for this button is the F5 key. As an additional point, it is sometimes useful to know how to execute your code without opening the IDE. To do this, you would type in -VBARUN into the command line, followed by you’re subroutine name. This command can conveniently be stored in a toolbar or pallette using the normal process for editing the user interface – CUI. Notice the preceeding “-” in front of the VBARUN command. You probably already know this is an AutoCAD® command modifier. The dash explicitly tells AutoCAD® to expect command line entry. If the dash is omitted, VBARUN opens a little dialog box, and you can pick your subroutine from there.

Step Three – Understanding the code

Maybe you executed the code and thought “that’s not very interesting..”. If so, I assure you this is the tip of a very large iceberg. In the code above, I’ve added comments in such a way that it explains it a little, but I’ll give a little more detail now.

Code is executed from the top down in the same manner you would read a book, unless you tell VB to do something else.

Dim MyString As String

This is the first line of code. This line creates what is known as a variable. The Keyword “Dim” is the part of the code that tells VB to create a variable. A variable is basically a memory bank with a name. The name of the “memory bank” or variable is MyString. We specified the name MyString, but it could have been called something else if we liked. The line Dim This_is_a_variable as string would be equally valid, but it’s a bit of a mouthful. Also, any reference to MyString in the code would need to be changed to This_is_a_variable in order for the code to work in the same way. The part of the code that says “As String” tells VB what type of variable it is. In this case, it is what is known as a String variable, or a Text-String. This basically means that anything that is attempted to be stored into the variable MyString should be interepretted as Text. If it is not text, VB will try to convert it to text. If it cannot, an error will occur with the message “Type Mismatch”

MyString = "Hello! This is text in a string variable!"

This line of code shows you how to set the contents of a variable. It is simply a case of stating that Variable = SOMETHING. The text after the equals sign must be enclosed inside quotation marks. If it was not enclosed in quotation marks, VB would try to execute the text as code, and an error would occur (the text would also be red). So enclosing it in quotation marks tells VB not to interpret this as code, but use it as a text value.

MsgBox MyString

This line of code causes a messagebox to be displayed. The command for doing so is MsgBox. The part following MsgBox in this instance is our variable called MyString, however we didn’t have to use a variable here. We could have explicitly put in any text we like enclosed in quotation marks, and it would be executed in the same way, displaying the inside of the quotation marks instead of the contents of the variable.

Dim Point(2) As Double

This should look quite familiar – again we’re declaring a variable. You’ll notice that it is a different type. In this instance it is a number. Specifically, a double precision floating point number, but we don’t need to know the details yet. You might also have noticed the brackets containing the number 2. The name of the variable is still just Point but this time it is an array. Think of an array as a list within that variable. This particular array has 3 elements to that list – 0, 1, and 2. We’ll probably talk more about arrays at another time.

Point(0) = 10 'This is x
Point(1) = 20 'This is y
Point(2) = 0 'This is z

Similarly to before, this is assigning values to the variable. However this time, as we’re dealing with an array, we need to specify which part of the list we want to assign our value to. Realise that all of the values are actually stored in the same variable, but just organised into a list.

Dim TextHeight As Double
TextHeight = 10

No problems here.

ThisDrawing.ModelSpace.AddText MyString, Point, TextHeight

The final line of code in this subroutine. The first part is quite self explanatory – Thisdrawing.Modelspace.Addtext. This adds some text into the modelspace of the active drawing. If there is no active drawing (i.e, they’re all closed) an error will occur. In order for AutoCAD® to be able to add text, it needs to know certain things: What text do you want to display? Where do you want to display it? What size do you want it to be? At this stage I will point out that the text we are adding is NOT MText. It is Text – what you would get by using the Text command in AutoCAD®. Conveniently, we’ve already set up some variables that contain the values we need. Pop them after Thisdrawing.Modelspace.Addtext in the right order, delimited with a comma, and you’ve now got some text in the modelspace of the current drawing.


I hope you found this a useful introduction – we haven’t don’t anything particularly useful yet, but there’s much much more great info where this came from. If you liked what you read I would encourage a subscription – you won’t regret it!

The CIRCLE command and the circle entity

The circle is one of those commands that can be very useful in the hands of those that know how. Obviously if you want to draw a circle this is what you need – but beyond that, circles have useful properties that make them very useful when trying to draw certain things. We’ll see some examples of what I mean later on in this post.

Normal Usage

 Invoke the CIRCLE command, and you will be prompted to supply a centre point for the circle. Next, you will be prompted for a radius. Simple.

There are some useful other ways to define your circle. One that is sometimes particularly useful is the TTR option, which is for drawing a circle of a given radius that is at tangents to two other objects.

Other Usage

One very useful little tactic sometimes is where you need to space out items, whatever that item may be, along a path. There are other ways of achieving this, but I find the circle method to be quite elegant and quick.

Draw a circle with your desired spacing as the radius. Begin the COPY command selecting the circle as your object to copy, and pick the centre point of the circle as your copy base point. Then, you can select the intersection between the circle and the path line as your insertion point for your new circle. Cunningly, we’re still in the middle of the copy command, and we have a new intersection to snap to as a result of the new circle we just created… snap to that intersection… then the next one… you get the idea. The notion using the COPY command in this sort of iterative way is very useful and will be discussed in greater detail when I write a post about the COPY command.