Variables and Const nts AutoCad Help

Until now, you haven’t learned about one big’ part of most actual procedure declarations: data types. Technically, all of the arguments and return values up to this point have been variants. You can think of a variant as a multipurpose data type that canhold anything. In this section, you’ll see that there are also special-purpose data types, as well as some other ways to store data than in simple variables.

Data Types

VBA supports ten specific types of data. these data types and the range of data that each one can hold

You can declare the type of a procedure argument, a variable, or a function return type with the As keyword. For example, you might rewrite the ShowSqUare, Return Square, and CallBoth procedures this way

You can explicitly declare a variable As Variant, and use it to hold any type of data that VBAis capable of handling. You can also leave the As clause off a variable declaration entirely, in which case VBAimplidtly provides a variant. While this technique does free you from having to worry about data typeS,’lt also means that VBAwon’t do any checking at nmtime to see whether data is reasonable. If you declare a variable As Integer and try to put ‘a character string in it,’VBA will Siv~ you an error; if you declare the same variable As Variant, VBAhas no idea that you didn’t want it to accept strings

Scope and Lifetime

Variables declared within procedures are local..They’re of use only to that procedure, and indeed, only when the procedure,is ~ But VBAprovides several other ways to declare variables. This Codefragment shows all ones you’ll’ commonly need

gstrSharedWithEveryone is a public variable (called a global variable in earlier versions of VBA). This variable can be used by any procedure in any module in the project.

• MstrSharedRightHere is a module-level variable. This variable can be used by any procedure in the module where it’s defined.
• VarArgl and varArg2 are local arguments. They can only be used by the proceduresin whose argument list they appear.
• IntI is a local variable. It can only be used by the procedure in which it is defined.
• IntJ is also a locat’variable. It can only be used by. the procedure in which it is defined.

This distinction between public, module-Ievel, and local variable is
commonly referred to as the scope of the variable. Using the previous example, gstrSharedWithEveryone has global scope, mStrSharedRightHere has module scope, and intI has local scope.

There’s also a second factor to consider in declaring variables,’ that of lifetime. Global and module scope variables have project lifetime: They are created when *e project is loaded, and if you set a value into one of these variables, they keep tflat value until the project is unloaded (or you deliberately set another value into. Local variables have procedure lifetime: They’re created when ‘you execute the procedure, and discarded when the procedure is finished. However, you can use the Static keyword (as shown for intJ above) to declare a local variable with project lifetime. What this means is that the value of the variable persists across calls to the procedure. If you run Helper more than once (and it contalns additional code, not shown here, to assign a value to the variable), you’ll find that intJ contains the last value you set into it, rather than being reinitialized each time.

The Option Explicit Statement

You may have noticed the line Opti on Exp1i ci t in the code example in the previous section. This is a VBAstatement that you can insert into any of your code modules (once per module, and by convention at the top). The effect of this statement is to tell VBA that you intend to explicitly declare all of your variables before using them. If you omit Opt; on Exp1ic; t, VBAwill automatically create a variant-type variable for any variable you use without declaration. This option can protect you against an annoying and hard-to-find error. For example, if you don’t have Option Explicit set, this is legal VBA.

Even though it’s legal, the Function as written will return 0, not 16, because one of the variable names is spelled differently than,the other two, causing VBA to assign it separate storage. If you b;y to run this procedure in a module with Option.  Exp set, though, you’ll get an immediate compilation error: Variable Not Defined from VBA.

Setting Opt; on Exp so important that there’s a way to tell VBAto do this for you in every new module. Select Tools >- Options >- Editor from the VBAdropdown menus-and you’ll get the Editor Options dialog box,. Check the Require Variable Declaration check box (by default it’s unchecked) and you’ll never have to worry about including Opt; on Exp1ici t again yourself. Make this the first thing you do after installing AutoCAD, before you write any code at all.

Constants

VBA supports constants-names for values that won’t change during the cburse of your application. You can use constants to make your code more readable.

For example, even though VBA doesn’t provide an automatic function to convert degrees into radians, it’s easy enough to write one:

Function DegreesToRadiansl(dblDegrees As Double)
As Double
DegreesToRadians1 – (dblDegrees / 180) * 3:14159
End Funetion

Although it’s easy enough to see what this example does,you can make it a bit clearer by using a constant to represent the magic number:

Function DegreesToRadians2(dblDegrees As Double) _
As Double
Const Pi – 3.14159
DegreesToRadians2 – (dblDegrees / 180) * Pi
End Funetion

Arrays

You can group VBAvariables into amiys-numbered collectiops of variables of the same type. To declare an array, you simply tell VBA how many elements it will have

Dim strK(1 To 5) As String

This creates an array, strK, with storage for five strings, numbered 1 through 5. You can assign values to members of an array, or read them out again:

Sub ArrayDemoO
Dim strK(l To 5) As String
strK(l) – “H”
strK(2) – ‘e’
strKq) – ·1 I
strK(4) – ‘1’
strK(S) – ‘0’
Debug.Print strK(l), strK(2), strK(3), _
strK(4), strK(5)
End Sub

Arrays tend to be of limited use in VBA, since in many instances, collections prove more useful. However, they’re critical for one thing in AutoCAD: the VBA representation of a point in AutoCAD’s Model Space is as an array of doubles. Here’s what the code for drawing a hne in AutoCAD might look like:

Sub DrawLineO
Dim ptStart(l To 3) As Double
Dim ptEnd(l To 3) As Double
ptStart(l) – 1
ptStart(2) – 1
ptStart(3) – 1
ptEnd(l) – 2
ptEnd(2) – 2
ptEnd(3) – 2
ThisDrawing.ModelSpace.AddLine ptStart, ptEnd
End Sub

Each of the arrays holds the information necessary to locate one point. The first, second, and third elements of the array tlold, respectively, the X-, y-, and z-coordinates of the point in AutoCAD’s model space

Colledions

VBA collections provide an alternative to arrays for keeping track of multiple items. Unlike arrays, which are designed to hold things that can be identified by number, collections are designed for random access. You can think of a collection as a place to stash anything you like and to retrieve it later by name. The CollectionDemo procedure demonstrates the syntax that you use working with collections:

Sub CollectionOemo()
Dim col As Collection
Add three items to the collection

       ‘Third’Set col – New Collection
col.Add S, ‘First’
col.Add 9, ‘Second’
col.Add 12,

Retrieve items by name
Debug.Print col.ItemC’First’)
Debug.Print colC’Second’)
Debug.Print colC”Third’)

Retrieve items by index
Debug.Print col.Item(1)
Debug.Print col(2)
Debug.Print col(3)

Remove an item from the collectipn
col.Remove 2

And show how many items are left
Debug.Print col.Count
End Sub

Although you declare a collection with the same Dim keyword that you use for other variables, you must also initialize the collection. That’s because a collection . is a type of object variable-one that has more complex properties than just a storage location for data. Initializing the variable is the purpose of this line:

Set col – New Collection

The New keyword tells VBAto create an object of the type Collection, and the Set keyword tells VBA to make the ,~l variable a way to refer to this new object.

Add is a method of the Collection object. ‘This method takes two rguments, the first being the item to add, and the second being a key value that can be used later to refer to the item. You can add anything to a collection. In this case, you’re adding the three numbers 9, 5, and 12.

The next two sections of the sample show that you can retrieve items either by key or by index (position) within the collection. Note that the keyword Item can be specified or omitted when using either syntax. That’s because Item is the default method of the collection object. Finally, you can use the Remove method to remove an item from a collection.. and the Count property to show the current number of items in a collection.

Posted on November 9, 2015 in Introduction to VBA I in Auto CAD

Share the Story

Back to Top
Share This