It was very confusing when I tried to learn VBA even though I was proficient in Lisp – the VBA jargon got me!
What are Objects, Properties, Methods, Constants and where do I go to access these?
The Answers as it relates to ICAD:
When the VB or VBA was written the developers decided using real world names to the various items in the program.
An Object is just that; it is any object that is exposed by VBA and ICAD is even an Object (it is king of the heap of objects and called the Application Object) Also a Line in your drawing is a Line Object (normally called a line entity), guess what they call a Circle – yes a Circle Object.
Properties are the settings of Objects, just like a Line in your drawing can have a color red – in VBA we say, the Color Property of the Line Object is set to Red and of course things like Layers are properties for all drawing entities – every user knows that all entities must have a layer and if one is not set then ICAD puts it on Layer 0 by default.
Methods are the activities we can do to Objects, if we rotate a line in ICAD – in VBA we say that we used the Rotate Method on a Line Object. So Methods can be considered like modifying Objects.
Constants are just special variables that can’t be changed and have user friendly names, just like CAD colors the Red = 1, Yellow = 2 and Green = 3 – in VBA constant vicRed = 1, vicYellow = 2 and vicGreen = 3.
The developers also created a development environment where VBA code is written and placed special icons adjacent to Properties, Methods and Constants to make it easy for us to understand what we are setting or altering.
The ICAD Object Model is a map displaying the VBA objects in ICAD and how to get to these. Just like a DOS command C:\ICAD\MyFile points to the directory named MyFile by going through the root directory in the C drive (C:\) then through the ICAD directory (ICAD\) in VBA it is just the same only instead of back slashes we use periods. To point to an Object in VBA we start at the root application object called IntelliCAD then to a document called ActiveDocument then to a space type called ModelSpace then to an entity, say a Line (IntelliCAD.ActiveDocument.ModelSpace.Line). To point to an circle object in paper space we use IntelliCAD.ActiveDocument.PaperSpace.Circle
The developers of ICAD helped us out by creating a special object called ThisDocument which is the ICAD Active Document. This can save us some typing by eliminating the “IntelliCAD.ActiveDocument” portion and replacing it with ThisDocument.
There are three areas in VBA where we go to – these are named ModelSpace, PaperSpace and Blocks to get to the drawing entities. Blocks contain drawing entities and this is the reason for the pathway.
When we want to interact with the user from the command prompt we go to an area in VBA called Utility (not much of a descriptive name) to select drawing entities and select positions such as corner or point. As an example to get the user to select a point we use ThisDocument.Utility.GetPoint(, "Place command prompt here").
Another important area is the Library (also not much of a descriptive name) to calculate, create or convert objects. The Library is separate from the ActiveDocument area, to access it we use Application Object. To create a Point Object at the drawing origin we use IntelliCAD.Library.CreatePoint(0,0,0)
I have covered a lot of basic information here and it is important you understand this so I suggest you go through each paragraph a few times to get your head around the jargon. Feel free to post any questions no matter what it is because I may not have fully explained the topic in sufficient detail and it will assist other readers.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#2
We can add drawing entities (I will call them Objects from now on) through Modelspace, Paperspace or Block path.
Using the Utility path we get user selected inputs such as GetDistance, GetCorner, GetPoint and GetEntity.
Non-Drawing related activities are accessed via the Library path to Convert (eg. Convert Points to an Array), Calculate (eg. Calculate a distance) or Create (eg. Create a Point).
These three paragraphs above represent the most used VBA paths and you don’t have to commit all the options to memory because the VBA IDE (Integrated Development Environment) provides automatic assistance. I feel there is no need to go into the use of the VBA IDE because it is so well covered in books on Microsoft Office products.
The Object Browser can be accessed by pressing F2 while in the VBA IDE and while it is similar in all Microsoft Office products, I will explain some of the features to help you explore the Object Model.
When you first open the Object Browser you will see two pull-down boxes and four windows (one grayed out at the bottom) The first pull-down box has <All Libraries> and exposes all the Object Libraries available. Selecting the pull-down you will see the following libraries:
CommonProjects – Automatic project available to all drawings.
IntelliCAD – All objects, properties, methods, constants and events for ICAD.
MSForms – All objects, properties, methods, constants and events for Forms.
Stdole – Standard Object Linking and Embedding - OLE Automation.
VBA - All objects, properties, methods, constants and events for VBA.
You may also see the name of any drawings that have code entered into them.
The second pull-down is used to allow searches for Library names for a user selected library (first pull-down). The results of a search appears in the first window named Search Results.
Under the search results window are two windows marked Classes and Members of ??????. The ????? depends what class has been highlighted in the Classes window.
Select IntelliCAD in the Library pull-down and the lower window that is grayed out will display:
Library IntelliCAD
C:\Your Path\ICADAUTO.DLL
IntelliCAD 2001 Object Library
This is the path to ICADAUTO.dll which has all the VBA Library Classes for IntelliCAD in a .dll file (dll = Dynamic Link Library)
Scrolling down in the Classes window will display some familiar names to ICAD users such as Circle, Line and Point. Highlight Circle in the Classes window will display in the lower window:
Class Circle
Member of IntelliCAD
Circle entity Object.
Highlight Copy in the Members of Circle window will display in the lower window:
Function Copy() As Entity
Member of IntelliCAD.Circle
Creates a copy of the entity.
Now select Library in the classes window to display a list of Members of Library and select CreatePoint. The lower window will display:
Function CreatePoint([X1 As Double], [Y1 As Double], [Z1 As Double]) As Point
Member of IntelliCAD.Library
Creates a new point object.
When typing code to create a point using the library you will see the CreatePoint method and the above list of arguments as assistance.
In the Member of ???? window:-
All Methods have a green block icon.
All Properties have a written paper with a pointing hand icon.
All Constants have a written paper icon.
All Events have a lightening strike icon.
(There are other icons and I will go into their detail later.)
Take time to familiarize yourself in the Object Browser, especially in the ModelSpace, PaperSpace, Block , Utility and Library classes.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
Using the Utility path we get user selected inputs such as GetDistance, GetCorner, GetPoint and GetEntity.
Non-Drawing related activities are accessed via the Library path to Convert (eg. Convert Points to an Array), Calculate (eg. Calculate a distance) or Create (eg. Create a Point).
These three paragraphs above represent the most used VBA paths and you don’t have to commit all the options to memory because the VBA IDE (Integrated Development Environment) provides automatic assistance. I feel there is no need to go into the use of the VBA IDE because it is so well covered in books on Microsoft Office products.
The Object Browser can be accessed by pressing F2 while in the VBA IDE and while it is similar in all Microsoft Office products, I will explain some of the features to help you explore the Object Model.
When you first open the Object Browser you will see two pull-down boxes and four windows (one grayed out at the bottom) The first pull-down box has <All Libraries> and exposes all the Object Libraries available. Selecting the pull-down you will see the following libraries:
CommonProjects – Automatic project available to all drawings.
IntelliCAD – All objects, properties, methods, constants and events for ICAD.
MSForms – All objects, properties, methods, constants and events for Forms.
Stdole – Standard Object Linking and Embedding - OLE Automation.
VBA - All objects, properties, methods, constants and events for VBA.
You may also see the name of any drawings that have code entered into them.
The second pull-down is used to allow searches for Library names for a user selected library (first pull-down). The results of a search appears in the first window named Search Results.
Under the search results window are two windows marked Classes and Members of ??????. The ????? depends what class has been highlighted in the Classes window.
Select IntelliCAD in the Library pull-down and the lower window that is grayed out will display:
Library IntelliCAD
C:\Your Path\ICADAUTO.DLL
IntelliCAD 2001 Object Library
This is the path to ICADAUTO.dll which has all the VBA Library Classes for IntelliCAD in a .dll file (dll = Dynamic Link Library)
Scrolling down in the Classes window will display some familiar names to ICAD users such as Circle, Line and Point. Highlight Circle in the Classes window will display in the lower window:
Class Circle
Member of IntelliCAD
Circle entity Object.
Highlight Copy in the Members of Circle window will display in the lower window:
Function Copy() As Entity
Member of IntelliCAD.Circle
Creates a copy of the entity.
Now select Library in the classes window to display a list of Members of Library and select CreatePoint. The lower window will display:
Function CreatePoint([X1 As Double], [Y1 As Double], [Z1 As Double]) As Point
Member of IntelliCAD.Library
Creates a new point object.
When typing code to create a point using the library you will see the CreatePoint method and the above list of arguments as assistance.
In the Member of ???? window:-
All Methods have a green block icon.
All Properties have a written paper with a pointing hand icon.
All Constants have a written paper icon.
All Events have a lightening strike icon.
(There are other icons and I will go into their detail later.)
Take time to familiarize yourself in the Object Browser, especially in the ModelSpace, PaperSpace, Block , Utility and Library classes.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#3
We have used the Object Browser to look at all those Objects in the classes window and noticed that there are familiar names such as Layer and Layers.
Notice they are both Members of IntelliCAD yet, Layer is a Layer Object and Layers is a Layer Collection Object. What is a Collection?
Collections are a group of like items that can be referenced as one unit. This is just like having ten lines in a drawing on different layers and colors. To obtain information on one line we could place them in a selection set and loop through each line to find the one we want, then obtain the needed information. Collections and selection sets are similar, only selection sets can contain differing objects while collections must have like items.
VBA has collections of like groups such as Layers where each Layer is given an index number accessed through the Item Method also a Add Method to Add items (like Layers) to the collection. Collections have a Count property that will return the total number of items and other Methods/Properties that may be peculiar to the items.
To test collections try the following:
In the VBA IDE select a drawing in the project window and add a Module.
Insert the following code:
Sub CountLayers()
MsgBox ThisDocument.Layers.Count
End Sub
Place your cursor in the middle of the code and press F5.
A message box will appear with the number of Layers that are in the drawing.
Try adding new layers and run the code again.
Now try it with LineTypes
Sub CountLineTypes()
MsgBox ThisDocument.Linetypes.Count
End Sub
Now try it with Blocks
Sub CountBlocks()
MsgBox ThisDocument.Blocks.Count
End Sub
You can try this with DimensionStyles, RegisteredApplications, SelectionSets, Viewports and Windows.
We can count how many items in a collection using the Count Property and now we need to use the Add Method to add an item.
We will start with layers and first count the number then add a layer then count the number again – just checking up on VBA.
Try this code:
Sub AddLayer()
MsgBox ThisDocument.Layers.Count
ThisDocument.Layers.Add "My New Layer"
MsgBox ThisDocument.Layers.Count
End Sub
Now try it again and an error message will appear|:
Method ‘Add’ of Object ‘IicadLayers’ Failed
This is because the layer “My New Layer” already existed and click Debug to highlight the line of code causing our error (called an exception in VBA).
Press the small blue square on the toolbar to reset our AddLayer subroutine.
Try the Add Method with other collections listed above and you can see how easy it is to add items to an IntelliCAD drawing.
Next I will show you how to test the items to find out if one already exists, to avoid the error problem.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
Notice they are both Members of IntelliCAD yet, Layer is a Layer Object and Layers is a Layer Collection Object. What is a Collection?
Collections are a group of like items that can be referenced as one unit. This is just like having ten lines in a drawing on different layers and colors. To obtain information on one line we could place them in a selection set and loop through each line to find the one we want, then obtain the needed information. Collections and selection sets are similar, only selection sets can contain differing objects while collections must have like items.
VBA has collections of like groups such as Layers where each Layer is given an index number accessed through the Item Method also a Add Method to Add items (like Layers) to the collection. Collections have a Count property that will return the total number of items and other Methods/Properties that may be peculiar to the items.
To test collections try the following:
In the VBA IDE select a drawing in the project window and add a Module.
Insert the following code:
Sub CountLayers()
MsgBox ThisDocument.Layers.Count
End Sub
Place your cursor in the middle of the code and press F5.
A message box will appear with the number of Layers that are in the drawing.
Try adding new layers and run the code again.
Now try it with LineTypes
Sub CountLineTypes()
MsgBox ThisDocument.Linetypes.Count
End Sub
Now try it with Blocks
Sub CountBlocks()
MsgBox ThisDocument.Blocks.Count
End Sub
You can try this with DimensionStyles, RegisteredApplications, SelectionSets, Viewports and Windows.
We can count how many items in a collection using the Count Property and now we need to use the Add Method to add an item.
We will start with layers and first count the number then add a layer then count the number again – just checking up on VBA.
Try this code:
Sub AddLayer()
MsgBox ThisDocument.Layers.Count
ThisDocument.Layers.Add "My New Layer"
MsgBox ThisDocument.Layers.Count
End Sub
Now try it again and an error message will appear|:
Method ‘Add’ of Object ‘IicadLayers’ Failed
This is because the layer “My New Layer” already existed and click Debug to highlight the line of code causing our error (called an exception in VBA).
Press the small blue square on the toolbar to reset our AddLayer subroutine.
Try the Add Method with other collections listed above and you can see how easy it is to add items to an IntelliCAD drawing.
Next I will show you how to test the items to find out if one already exists, to avoid the error problem.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#4
Errors in any code should be handled gracefully and there are various ways to handle these. One method is to check the input prior to using any methods just in case the name exists in a collection.
This is where VBA Functions come in handy, check out the Library VBA in the Object Browser and look into Classes Strings. There are many methods to handle strings and I suggest you look at StrComp:
Function StrComp(String1, String2, [Compare As VbCompareMethod = vbBinaryCompare])
Member of VBA.Strings
This enables differing types of string comparison through the argument Compare As VbCompareMethod =
In the lower grayed out window of the Object Browser select the green “VbCompareMethod” and you will be transported to the Class VbCompareMethod. You can see that there are three members Const vbBinaryCompare = 0, Const vbTextCompare = 1and Const vbDatabaseCompare = 2. These constants offer different types of comparison and below is an explanation:
vbBinaryCompare uses internal sort order of each binary representation, in other words capitals are not equal to lower case characters – A is not equal to a.
vbTextCompare uses the text sort order, in other words A is equal to a.
vbDatabaseCompare is used for Microsoft Access Only to test the locale identification of the current database.
The Function StrComp will return an Integer bases on the string comparison:
String1 = String2 then 0 is returned
String1 is alphabetically greater than String2 then 1 is returned
String1 is alphabetically less than String2 then -1 is returned
String1 is Null or String2 is Null then Null is returned
Sorry for boring you!.
Lets get into using the StrComp Function
To avoid an error we need to loop through each layer in the drawing and compare the Proposed Layer Name to each Existing Layer name and if the StrComp returns 0, we know that the Layer exists and we shouldn’t try and add the Proposed Layer.
We use For Each – Next to loop through the Layers:
Dimension the variable objLayer to a Layer in the drawing:
Dim objLayer As IntelliCAD.Layer
This “For Each Next” will loop through each Layer in the drawing and stop looping if no more Layers are found:
For Each objLayer In IntelliCAD.ActiveDocument.Layers
Next objLayer
This “If Then” statement will Display a message if the Layer names are equal:
If StrComp(ProposedLayer, objLayer.Name, vbTextCompare) = 0 Then
MsgBox "The Layer Name Exists"
End If
The Complete subroutine:
Sub TestLayerNames()
Dim ProposedLayer As String
Dim objLayer As IntelliCAD.Layer
' name of Layer to check
ProposedLayer = "0"
For Each objLayer In IntelliCAD.ActiveDocument.Layers
If StrComp(ProposedLayer, objLayer.Name, vbTextCompare) = 0 Then
MsgBox "The Layer Name Exists"
End If
Next objLayer
End Sub
Change the “0” to a layer name that doesn’t exist to see what happens.
Here is the code that will test if the Layer exists and if not it will add the layer to the drawing:
Public Sub MakeLayer(MLayer As String)
' This routine will create a layer when it is not in drawing
' Dimension the variables
Dim LayerFlag As Integer
Dim objMLayer As IntelliCAD.Layer
'Make sure the LayerFlag is set to 0
LayerFlag = 0
' Loop through each Layer
For Each objMLayer In IntelliCAD.ActiveDocument.Layers
'Compare the name to our MLayer string. if it exists set the LayerFlag to 1
If StrComp(objMLayer.Name, MLayer, vbTextCompare) = 0 Then LayerFlag = 1
Next objMLayer
' If the LayerFlag is 0 then no layer name exists for our MLayer string and we must make it.
If LayerFlag = 0 Then
Set objMLayer = IntelliCAD.ActiveDocument.Layers.Add(MLayer)
End If
End Sub
To use the MakeLayer code we must use another subroutine's code such as:
Sub UsingMakeLayer()
MakeLayer "MyLayerName"
End Sub
This Sub UsingMakeLayer calls the MakeLayer Sub and supplies the name of the layer we want "MyLayerName". If MyLayerName is already a layer in the drawing nothing is added however, if it is not in the drawing then our MakeLayer Sub will create it for us.
Note I used Public in front of the Sub in our MakeLayer code. Making a Sub Public means that it can be called from any Module or Class Module. If we place Private in front of a Sub the code can only be called from within the module where our code resides.
You can try this with DimensionStyles, RegisteredApplications, SelectionSets, Viewports and Windows to compare the differing string names and only add the new name when these don’t exist.
Well that covers Collections that we can count and add with error trapping to ensure our code does not fail.
Next we will get into adding drawing objects into our drawing.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
[This message has been edited by John Finlay (edited 08-24-2001).]
[This message has been edited by John Finlay (edited 10-08-2001).]
This is where VBA Functions come in handy, check out the Library VBA in the Object Browser and look into Classes Strings. There are many methods to handle strings and I suggest you look at StrComp:
Function StrComp(String1, String2, [Compare As VbCompareMethod = vbBinaryCompare])
Member of VBA.Strings
This enables differing types of string comparison through the argument Compare As VbCompareMethod =
In the lower grayed out window of the Object Browser select the green “VbCompareMethod” and you will be transported to the Class VbCompareMethod. You can see that there are three members Const vbBinaryCompare = 0, Const vbTextCompare = 1and Const vbDatabaseCompare = 2. These constants offer different types of comparison and below is an explanation:
vbBinaryCompare uses internal sort order of each binary representation, in other words capitals are not equal to lower case characters – A is not equal to a.
vbTextCompare uses the text sort order, in other words A is equal to a.
vbDatabaseCompare is used for Microsoft Access Only to test the locale identification of the current database.
The Function StrComp will return an Integer bases on the string comparison:
String1 = String2 then 0 is returned
String1 is alphabetically greater than String2 then 1 is returned
String1 is alphabetically less than String2 then -1 is returned
String1 is Null or String2 is Null then Null is returned
Sorry for boring you!.
Lets get into using the StrComp Function
To avoid an error we need to loop through each layer in the drawing and compare the Proposed Layer Name to each Existing Layer name and if the StrComp returns 0, we know that the Layer exists and we shouldn’t try and add the Proposed Layer.
We use For Each – Next to loop through the Layers:
Dimension the variable objLayer to a Layer in the drawing:
Dim objLayer As IntelliCAD.Layer
This “For Each Next” will loop through each Layer in the drawing and stop looping if no more Layers are found:
For Each objLayer In IntelliCAD.ActiveDocument.Layers
Next objLayer
This “If Then” statement will Display a message if the Layer names are equal:
If StrComp(ProposedLayer, objLayer.Name, vbTextCompare) = 0 Then
MsgBox "The Layer Name Exists"
End If
The Complete subroutine:
Sub TestLayerNames()
Dim ProposedLayer As String
Dim objLayer As IntelliCAD.Layer
' name of Layer to check
ProposedLayer = "0"
For Each objLayer In IntelliCAD.ActiveDocument.Layers
If StrComp(ProposedLayer, objLayer.Name, vbTextCompare) = 0 Then
MsgBox "The Layer Name Exists"
End If
Next objLayer
End Sub
Change the “0” to a layer name that doesn’t exist to see what happens.
Here is the code that will test if the Layer exists and if not it will add the layer to the drawing:
Public Sub MakeLayer(MLayer As String)
' This routine will create a layer when it is not in drawing
' Dimension the variables
Dim LayerFlag As Integer
Dim objMLayer As IntelliCAD.Layer
'Make sure the LayerFlag is set to 0
LayerFlag = 0
' Loop through each Layer
For Each objMLayer In IntelliCAD.ActiveDocument.Layers
'Compare the name to our MLayer string. if it exists set the LayerFlag to 1
If StrComp(objMLayer.Name, MLayer, vbTextCompare) = 0 Then LayerFlag = 1
Next objMLayer
' If the LayerFlag is 0 then no layer name exists for our MLayer string and we must make it.
If LayerFlag = 0 Then
Set objMLayer = IntelliCAD.ActiveDocument.Layers.Add(MLayer)
End If
End Sub
To use the MakeLayer code we must use another subroutine's code such as:
Sub UsingMakeLayer()
MakeLayer "MyLayerName"
End Sub
This Sub UsingMakeLayer calls the MakeLayer Sub and supplies the name of the layer we want "MyLayerName". If MyLayerName is already a layer in the drawing nothing is added however, if it is not in the drawing then our MakeLayer Sub will create it for us.
Note I used Public in front of the Sub in our MakeLayer code. Making a Sub Public means that it can be called from any Module or Class Module. If we place Private in front of a Sub the code can only be called from within the module where our code resides.
You can try this with DimensionStyles, RegisteredApplications, SelectionSets, Viewports and Windows to compare the differing string names and only add the new name when these don’t exist.
Well that covers Collections that we can count and add with error trapping to ensure our code does not fail.
Next we will get into adding drawing objects into our drawing.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
[This message has been edited by John Finlay (edited 08-24-2001).]
[This message has been edited by John Finlay (edited 10-08-2001).]
#5
Adding lines, arcs, circles, text and point entities to our drawing via VBA is really quite easy, you just decide which space (paper/model) to put it and give the object the correct arguments.
A line needs start and end points, so to place it in ModelSpace use AddLine Method:
ThisDocument.ModelSpace.AddLine objStartPnt, objEndPnt
There is a problem when we want to access the properties of our newly created line because there is no pointer to our Line Object.
To Set an Object Pointer use:
Set objLine = ThisDocument.ModelSpace.AddLine(objStartPnt, objEndPnt)
Notice we added parenthesis to the AddLine arguments when we set a pointer to the object. When a Method or Function returns values their arguments must be enclosed with parenthesis and if no value is needed then no parenthesis.
Now that we have a pointer to the Object we can manipulate the Object’s properties such as Layer, Color and even its start and end points.
To get our line into the drawing database is only the first step - it also helps if we display it on the screen and to do this we use the Update Method.
We know that all entities have at least one point (its insertion point) where our line needs two points.
Points are also Objects and there are two methods to Set pointers to a Point:
1/ Create the point using the Library class.
2/ Allow the user to select a point using the Utility class.
We are here to learn so we will use both methods – The Library class for the start point and Utility class for the end point.
In a drawing insert a module to store our code and call our subroutine MyNewLine.
Code Start …………………………….
Sub MyNewLine()
' Dimension variables
Dim objLine As Line
Dim objStartPnt As Point
Dim objEndPnt As Point
' use the Library class to create a point at the drawing origin
Set objStartPnt = Library.CreatePoint(0, 0, 0)
' use the Utility class to select a point with a rubber band to assist display
Set objEndPnt = ThisDocument.Utility.GetPoint(objStartPnt, "Select the end of line")
' add the Line to the drawing database
Set objLine = ThisDocument.ModelSpace.AddLine(objStartPnt, objEndPnt)
' update the line on the screen
objLine.Update
End Sub
Code End ……………………………….
If we don’t want to use the rubber band just leave out the objStartPnt in our Utility class method as below:
Set objEndPnt = ThisDocument.Utility.GetPoint(, "Select the end of line")
Rem out the objLine.Update by placing an apostrophe in front of it so the code is disabled and see what happens. Yes - the line is not displayed on our screen until we regenerate the drawing.
Next we will add a circle and call our subroutine MyNewCircle and place it in the existing drawing module.
Code Start ……………………………….
Sub MyNewCircle()
' Dimension variables
Dim objCircle As IntelliCAD.Circle
Dim objCenterPnt As Point
Dim myRadius As Double
' use the Utility class to select a center point for our circle
Set objCenterPnt = ThisDocument.Utility.GetPoint(, "Select the center point")
' the value of our variable for the radius
myRadius = 100.5
' add the Line to the drawing database
Set objCircle = ThisDocument.ModelSpace.AddCircle(objCenterPnt, myRadius)
' update the line on the screen
objCircle.Update
End Sub
Code End ……………………………….
Notice we used IntelliCAD.Circle when we dimensioned our objCircle instead of Circle. There appears to be some keyword error in ICAD’s VBA.
MyRadius is dimensioned as a double because all the variables used to input sizes in ICAD use the Double (double-precision floating-point) data type.
You can see a familiar pattern with the line and circle; both need point/s and a pointer to update the object on the screen.
An arc object is like a circle with a starting and ending angle and a point entity just needs the insertion point.
Text is similar to our samples above and in the next lesson we will insert some text with a prefix such as Room 1, Room 2 Room….n and have VBA automatically increment the numbers for us.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
A line needs start and end points, so to place it in ModelSpace use AddLine Method:
ThisDocument.ModelSpace.AddLine objStartPnt, objEndPnt
There is a problem when we want to access the properties of our newly created line because there is no pointer to our Line Object.
To Set an Object Pointer use:
Set objLine = ThisDocument.ModelSpace.AddLine(objStartPnt, objEndPnt)
Notice we added parenthesis to the AddLine arguments when we set a pointer to the object. When a Method or Function returns values their arguments must be enclosed with parenthesis and if no value is needed then no parenthesis.
Now that we have a pointer to the Object we can manipulate the Object’s properties such as Layer, Color and even its start and end points.
To get our line into the drawing database is only the first step - it also helps if we display it on the screen and to do this we use the Update Method.
We know that all entities have at least one point (its insertion point) where our line needs two points.
Points are also Objects and there are two methods to Set pointers to a Point:
1/ Create the point using the Library class.
2/ Allow the user to select a point using the Utility class.
We are here to learn so we will use both methods – The Library class for the start point and Utility class for the end point.
In a drawing insert a module to store our code and call our subroutine MyNewLine.
Code Start …………………………….
Sub MyNewLine()
' Dimension variables
Dim objLine As Line
Dim objStartPnt As Point
Dim objEndPnt As Point
' use the Library class to create a point at the drawing origin
Set objStartPnt = Library.CreatePoint(0, 0, 0)
' use the Utility class to select a point with a rubber band to assist display
Set objEndPnt = ThisDocument.Utility.GetPoint(objStartPnt, "Select the end of line")
' add the Line to the drawing database
Set objLine = ThisDocument.ModelSpace.AddLine(objStartPnt, objEndPnt)
' update the line on the screen
objLine.Update
End Sub
Code End ……………………………….
If we don’t want to use the rubber band just leave out the objStartPnt in our Utility class method as below:
Set objEndPnt = ThisDocument.Utility.GetPoint(, "Select the end of line")
Rem out the objLine.Update by placing an apostrophe in front of it so the code is disabled and see what happens. Yes - the line is not displayed on our screen until we regenerate the drawing.
Next we will add a circle and call our subroutine MyNewCircle and place it in the existing drawing module.
Code Start ……………………………….
Sub MyNewCircle()
' Dimension variables
Dim objCircle As IntelliCAD.Circle
Dim objCenterPnt As Point
Dim myRadius As Double
' use the Utility class to select a center point for our circle
Set objCenterPnt = ThisDocument.Utility.GetPoint(, "Select the center point")
' the value of our variable for the radius
myRadius = 100.5
' add the Line to the drawing database
Set objCircle = ThisDocument.ModelSpace.AddCircle(objCenterPnt, myRadius)
' update the line on the screen
objCircle.Update
End Sub
Code End ……………………………….
Notice we used IntelliCAD.Circle when we dimensioned our objCircle instead of Circle. There appears to be some keyword error in ICAD’s VBA.
MyRadius is dimensioned as a double because all the variables used to input sizes in ICAD use the Double (double-precision floating-point) data type.
You can see a familiar pattern with the line and circle; both need point/s and a pointer to update the object on the screen.
An arc object is like a circle with a starting and ending angle and a point entity just needs the insertion point.
Text is similar to our samples above and in the next lesson we will insert some text with a prefix such as Room 1, Room 2 Room….n and have VBA automatically increment the numbers for us.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#6
For our text prefix routine we will use a built in VBA display method named InputBox (Function).
To use the InputBox Function (a Function returns a variable) just type Variable = InputBox (arguments) in any module.
Arguments List:
Prompt – A String the user sets in the prompt area (required)
Title – A String to display in the Title Bar (optional)
Default – A String that is defaulted into the edit area (optional)
also
xpos, ypos, helpfile and context are all optional and rarely used.
You can tell if an argument is optional or not because optional arguments are displayed in square brackets in the auto list (the list that VBA displays as assistance to the user when writing code) and in the Object Browser.
Here is the TextPlusOne subroutine”
Start Code ……………………………………
Sub TextPlusOne()
' Dimension Variables
Dim PrefixText As String
Dim StartNumber As String
Dim objPnt As Point
Dim FullText As String
Dim objText As Text
' use an InputBox Functions to obtain user inputs
PrefixText = InputBox("Text Prefix", "CMS Tutorials")
StartNumber = InputBox("Start Number", "CMS Tutorials")
' start a loop routine using Do Until there is no StartNumber entered
Do Until StartNumber = ""
' use Utility clas to obtain a text insertion point from the user
Set objPnt = IntelliCAD.ActiveDocument.Utility.GetPoint(, "Text Location")
' build the text from the prefix and the start number
FullText = PrefixText & " " & StartNumber
' add the text to the drawing database and update to screen
Set objText = IntelliCAD.ActiveDocument.ModelSpace.AddText(FullText, objPnt, 500#)
objText.Update
' allow the user to change the number or accept the default increment
StartNumber = InputBox("Start Number" & vbCr & vbCr & "Press the keyboard <ENTER>To Continue", "CMS Tutorials", CStr(CInt(StartNumber) + 1))
Loop
End Sub
End Code ………………………………………
The routine is quite simple, it prompts the user for a prefix to the text – try Room. Another prompt requests the staring number then the insertion point for the text.
The loop will continue to prompt for additional numbers and will add one to the last number used. To speed the process the user can accept the default incremented number by pressing <Enter> on the keyboard and select insertion point.
The routine exits when the input box returns no text from either selecting cancel or delete default and press <Enter> on keyboard.
We have used some new VBA methods in this routine such as vbCr, CStr and CInt.
vbCr – stands for carriage return and allows the start of text on a new line.
CStr – Changes the variable to a String.
Cint – Changes the variable to an Integer.
We needed to change our incrementing number to an integer than add 1 then return it to a string.
When the Cancel button is selected on InputBox it will return an empty string and this is what we use to cancel our Do Until Loop.
Next we will cover the use of another built in VBA method called MsgBox and use an If Then Else statement to enhance our Prefix text incrementing routine.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
To use the InputBox Function (a Function returns a variable) just type Variable = InputBox (arguments) in any module.
Arguments List:
Prompt – A String the user sets in the prompt area (required)
Title – A String to display in the Title Bar (optional)
Default – A String that is defaulted into the edit area (optional)
also
xpos, ypos, helpfile and context are all optional and rarely used.
You can tell if an argument is optional or not because optional arguments are displayed in square brackets in the auto list (the list that VBA displays as assistance to the user when writing code) and in the Object Browser.
Here is the TextPlusOne subroutine”
Start Code ……………………………………
Sub TextPlusOne()
' Dimension Variables
Dim PrefixText As String
Dim StartNumber As String
Dim objPnt As Point
Dim FullText As String
Dim objText As Text
' use an InputBox Functions to obtain user inputs
PrefixText = InputBox("Text Prefix", "CMS Tutorials")
StartNumber = InputBox("Start Number", "CMS Tutorials")
' start a loop routine using Do Until there is no StartNumber entered
Do Until StartNumber = ""
' use Utility clas to obtain a text insertion point from the user
Set objPnt = IntelliCAD.ActiveDocument.Utility.GetPoint(, "Text Location")
' build the text from the prefix and the start number
FullText = PrefixText & " " & StartNumber
' add the text to the drawing database and update to screen
Set objText = IntelliCAD.ActiveDocument.ModelSpace.AddText(FullText, objPnt, 500#)
objText.Update
' allow the user to change the number or accept the default increment
StartNumber = InputBox("Start Number" & vbCr & vbCr & "Press the keyboard <ENTER>To Continue", "CMS Tutorials", CStr(CInt(StartNumber) + 1))
Loop
End Sub
End Code ………………………………………
The routine is quite simple, it prompts the user for a prefix to the text – try Room. Another prompt requests the staring number then the insertion point for the text.
The loop will continue to prompt for additional numbers and will add one to the last number used. To speed the process the user can accept the default incremented number by pressing <Enter> on the keyboard and select insertion point.
The routine exits when the input box returns no text from either selecting cancel or delete default and press <Enter> on keyboard.
We have used some new VBA methods in this routine such as vbCr, CStr and CInt.
vbCr – stands for carriage return and allows the start of text on a new line.
CStr – Changes the variable to a String.
Cint – Changes the variable to an Integer.
We needed to change our incrementing number to an integer than add 1 then return it to a string.
When the Cancel button is selected on InputBox it will return an empty string and this is what we use to cancel our Do Until Loop.
Next we will cover the use of another built in VBA method called MsgBox and use an If Then Else statement to enhance our Prefix text incrementing routine.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#7
The MsgBox Function is a very useful way to obtain user interaction on simple questions.
To use the MsgBox Function simply add:
VariableName = MsgBox(arguments)
The arguments include:
Prompt – A string to display the prompt to the user.
Buttons – Integer to display various Buttons for options to the user. (all buttons have named constants) (optional)
Title – String display title of message box.(optional)
Helpfile and context are both optional and rarely used
When buttons are selected by the user, a value is stored in the VariableName as below:
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7
I have included the full code for our new TextPlusOne subroutine and highlighted the new code with ******* New
Start Code ……………………………………….
Sub TextPlusOne()
' Dimension Variables
Dim PrefixText As String
Dim StartNumber As String
Dim objPnt As Point
Dim FullText As String
Dim objText As Text
Dim PMSpace As String ‘****** New
' use MsgBox to obtain user information ****** New
PMSpace = MsgBox("Do You want to add Text in Paperspace?", vbYesNo + vbQuestion, "CMS Tutorial")
' use an InputBox Functions to obtain user inputs
PrefixText = InputBox("Text Prefix", "CMS Tutorials")
StartNumber = InputBox("Start Number", "CMS Tutorials")
' start a loop routine using Do Until there is no StartNumber entered
Do Until StartNumber = ""
' use Utility clas to obtain a text insertion point from the user
Set objPnt = IntelliCAD.ActiveDocument.Utility.GetPoint(, "Text Location")
' build the text from the prefix and the start number
FullText = PrefixText & " " & StartNumber
' add the text to the drawing database in either PaperSpace or ModelSpace then update to screen
If PMSpace = 6 Then ‘******** New
Set objText = IntelliCAD.ActiveDocument.PaperSpace.AddText(FullText, objPnt, 500#)
Else
Set objText = IntelliCAD.ActiveDocument.ModelSpace.AddText(FullText, objPnt, 500#)
End If
objText.Update
' allow the user to change the number or accept the default increment
StartNumber = InputBox("Start Number" & vbCr & vbCr & "Press the keyboard <ENTER>To Continue", "CMS Tutorials", CStr(CInt(StartNumber) + 1))
Loop
End Sub
End Code ……………………………………….
When using buttons in our MsgBox I have used the constant vbYesNo (= 4) and added vbQuestion (= 32) just as if these constants were values.
In accordance with our Function returned values, if the user selects the No button a 7 is returned and if Yes is selected a 6 is returned to our variable named PMSpace.
Testing our user selection in a If Then Else statement for 6 means the uses of Paper Space and if not 6 then use Model Space (default). We could use an If Then statement and test for 7 to select Model Space, but because there are only two selections and we want to use Model Space as our default, the 7 is ignored.
Next we will look at the Library classes.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
To use the MsgBox Function simply add:
VariableName = MsgBox(arguments)
The arguments include:
Prompt – A string to display the prompt to the user.
Buttons – Integer to display various Buttons for options to the user. (all buttons have named constants) (optional)
Title – String display title of message box.(optional)
Helpfile and context are both optional and rarely used
When buttons are selected by the user, a value is stored in the VariableName as below:
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7
I have included the full code for our new TextPlusOne subroutine and highlighted the new code with ******* New
Start Code ……………………………………….
Sub TextPlusOne()
' Dimension Variables
Dim PrefixText As String
Dim StartNumber As String
Dim objPnt As Point
Dim FullText As String
Dim objText As Text
Dim PMSpace As String ‘****** New
' use MsgBox to obtain user information ****** New
PMSpace = MsgBox("Do You want to add Text in Paperspace?", vbYesNo + vbQuestion, "CMS Tutorial")
' use an InputBox Functions to obtain user inputs
PrefixText = InputBox("Text Prefix", "CMS Tutorials")
StartNumber = InputBox("Start Number", "CMS Tutorials")
' start a loop routine using Do Until there is no StartNumber entered
Do Until StartNumber = ""
' use Utility clas to obtain a text insertion point from the user
Set objPnt = IntelliCAD.ActiveDocument.Utility.GetPoint(, "Text Location")
' build the text from the prefix and the start number
FullText = PrefixText & " " & StartNumber
' add the text to the drawing database in either PaperSpace or ModelSpace then update to screen
If PMSpace = 6 Then ‘******** New
Set objText = IntelliCAD.ActiveDocument.PaperSpace.AddText(FullText, objPnt, 500#)
Else
Set objText = IntelliCAD.ActiveDocument.ModelSpace.AddText(FullText, objPnt, 500#)
End If
objText.Update
' allow the user to change the number or accept the default increment
StartNumber = InputBox("Start Number" & vbCr & vbCr & "Press the keyboard <ENTER>To Continue", "CMS Tutorials", CStr(CInt(StartNumber) + 1))
Loop
End Sub
End Code ……………………………………….
When using buttons in our MsgBox I have used the constant vbYesNo (= 4) and added vbQuestion (= 32) just as if these constants were values.
In accordance with our Function returned values, if the user selects the No button a 7 is returned and if Yes is selected a 6 is returned to our variable named PMSpace.
Testing our user selection in a If Then Else statement for 6 means the uses of Paper Space and if not 6 then use Model Space (default). We could use an If Then statement and test for 7 to select Model Space, but because there are only two selections and we want to use Model Space as our default, the 7 is ignored.
Next we will look at the Library classes.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
#8
The Library classes are used for non-drawing activities to create, convert and calculate.
To check out what we can do in the Library classes, type Library. In ant module and an auto list appears.
We will explore some of the most popular methods:
Create:
The most used Library function is CreatePoint to create a point with x, y and z co-ordinates.
Example.
MyPoint = Library.CreatePoint(10.5, 52.3, 8.9)
We used the CreatePoint in our Subroutine MyNewLine above to create a point at the origin. It can be used to obtain a constant starting point for drawing activities.
Convert:
There may be times when we need to convert information and an example is ConvertPointToArray and below is an example:
Sub ArrayConvert ()
Dim myElement As Variant
Dim myArray() As Double
Dim Pnt As Point
' Create Point
Set Pnt = Library.CreatePoint(100.5, 50.25, 3.175)
' Convert the point to an array
myArray = Library.ConvertPointToArray(Pnt, True)
' Loop through each element in the array and display a message
For Each myElement In myArray()
MsgBox myElement
Next myElement
End Sub
We can see the point Pnt converted into an array of Doubles (myArray)
One of the major advantages in IntelliCAD is the Point Object that uses x, y and z as properties, where AutoCAD uses arrays for the points.
Calculate:
The most used function is CalculateDistance that calculates the distance between two points.
Here is an example using a 3 – 4 – 5 right angled triangle:
Sub MyDistCal()
Dim Pnt1 As Point
Dim Pnt2 As Point
Dim myDist As Double
' Create Points
Set Pnt1 = Library.CreatePoint(0, 0, 0)
Set Pnt2 = Library.CreatePoint(4, 3, 0)
' calculate the distance
myDist = Library.CalculateDistance(Pnt1, Pnt2)
' display the distance in a message box
MsgBox myDist
End Sub
We have covered the very basic drawing Objects and there are many examples in the ICAD Help.
You now know your way around the Object Model and can create lines and circles using Paperspace and Modelspace. You can also obtain information from the user with the Utility classes and create, convert and calculate using Library classes.
Next we will cover selection sets to allow us to work on a large selection of entities –We are advancing to the intermediate stage and I will create a new thread VBA the Intermediate.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au
To check out what we can do in the Library classes, type Library. In ant module and an auto list appears.
We will explore some of the most popular methods:
Create:
The most used Library function is CreatePoint to create a point with x, y and z co-ordinates.
Example.
MyPoint = Library.CreatePoint(10.5, 52.3, 8.9)
We used the CreatePoint in our Subroutine MyNewLine above to create a point at the origin. It can be used to obtain a constant starting point for drawing activities.
Convert:
There may be times when we need to convert information and an example is ConvertPointToArray and below is an example:
Sub ArrayConvert ()
Dim myElement As Variant
Dim myArray() As Double
Dim Pnt As Point
' Create Point
Set Pnt = Library.CreatePoint(100.5, 50.25, 3.175)
' Convert the point to an array
myArray = Library.ConvertPointToArray(Pnt, True)
' Loop through each element in the array and display a message
For Each myElement In myArray()
MsgBox myElement
Next myElement
End Sub
We can see the point Pnt converted into an array of Doubles (myArray)
One of the major advantages in IntelliCAD is the Point Object that uses x, y and z as properties, where AutoCAD uses arrays for the points.
Calculate:
The most used function is CalculateDistance that calculates the distance between two points.
Here is an example using a 3 – 4 – 5 right angled triangle:
Sub MyDistCal()
Dim Pnt1 As Point
Dim Pnt2 As Point
Dim myDist As Double
' Create Points
Set Pnt1 = Library.CreatePoint(0, 0, 0)
Set Pnt2 = Library.CreatePoint(4, 3, 0)
' calculate the distance
myDist = Library.CalculateDistance(Pnt1, Pnt2)
' display the distance in a message box
MsgBox myDist
End Sub
We have covered the very basic drawing Objects and there are many examples in the ICAD Help.
You now know your way around the Object Model and can create lines and circles using Paperspace and Modelspace. You can also obtain information from the user with the Utility classes and create, convert and calculate using Library classes.
Next we will cover selection sets to allow us to work on a large selection of entities –We are advancing to the intermediate stage and I will create a new thread VBA the Intermediate.
------------------
Regards
John Finlay
Don't want to post a question - email me direct on john@acecad.com.au