You are on page 1of 30

VBA TUTORIAL

VBA TUTORIAL

2
TABLE OF CONTENTS
1. VBA GENERAL ............................................................................................................................... 3
1.1. Introduction ............................................................................................................................. 3
1.2. Getting Started ........................................................................................................................ 3
1.3. The VBA Hierarchy ................................................................................................................... 6
1.4. Programming essentials .......................................................................................................... 7
1.4.1. The Sub Procedure .......................................................................................................... 7
1.4.2. Variables .......................................................................................................................... 8
1.4.3. IfThenElse ................................................................................................................. 10
1.4.4. Fornext ........................................................................................................................ 12
1.4.5. Do whileloop ............................................................................................................... 14
1.4.6. Functions ....................................................................................................................... 15
1.5. More VBA .............................................................................................................................. 17
1.5.1. Comments ..................................................................................................................... 17
1.5.2. Logical operators ........................................................................................................... 17
1.5.3. Basic string handling ...................................................................................................... 18
1.5.4. IsNumeric() .................................................................................................................... 19
1.5.5. Decimal seperator ......................................................................................................... 19
1.5.6. Topics to check out yourself .......................................................................................... 20
2. VBA for Pythagoras ........................................................................................................................ 21
2.1. The Pythagoras Object Model ............................................................................................... 21
2.1.1. In general ....................................................................................................................... 21
2.1.2. Hierarchy of the pythagoras object model .................................................................... 21
2.1.3. Using the VBA manual ................................................................................................... 22
2.2. VBA for Pythagoras in practice .............................................................................................. 22
2.2.1. Example 1: Change comment ........................................................................................ 22
2.2.2. Example 2: Average point .............................................................................................. 24
2.2.3. Example 3: Using the PrivateTool .................................................................................. 26
2.3. Making Larger projects .......................................................................................................... 27
2.3.1. Sub OnStartUp ............................................................................................................... 27
2.3.2. Managing your modules and forms .............................................................................. 29
2.4. The End .................................................................................................................................. 30

VBA TUTORIAL

3
1. VBA GENERAL

1.1. INTRODUCTION
Why use VBA? Pythagoras VBA is a programming environment in Pythagoras that allows you to:
Automate repeating actions and processes.
Add your own features.
VBA stands for Visual Basic for Applications. VBA is an easy-to-learn, error-tolerant programming
language.
The programming language "Pythagoras VBA" is nearly identical to the language used by the Mi-
crosoft products Visual Basic and MS-Office VBA. The way Pythagoras objects (Document, Point, Line,
etc) are accessed from VBA is similar to the access of objects in the MS-Office products.
In this chapter (1. VBA General), the generally used controls will be discussed, without using Py-
thagoras. If you already have a basic knowledge of VB or VBA, it is recommended to forward to the
next chapter. In this next chapter (2. VBA for Pythagoras), the Pythagoras Object Model is elaborated
using examples.
This tutorial introduces you to VBA. No prior knowledge is needed. Like all tutorials, it doesnt cover
all VBA functionalities. If you want a more thorough knowledge of VBA in general after completing
this tutorial, great books can be found. And of course, since VBA is widely used language, there are
plenty of websites and forums who provide information about VBA. All the functionalities of VBA for
Pythagoras are also listed in our VBA Manual, which can be found on our website. It can be used as a
reference manual.
1.2. GETTING STARTED
Whats a macro? A macro is a set of instructions you give to Pythagoras in the VBA language. The
design and maintenance of a macro is best done in a Document Library. Another option is the System
Library. If you use a document library, the macro is embedded in the document. A library can contain
multiple macros.
VBA TUTORIAL

4
STEP 1: Open a new document and give the document a name.
STEP 2: Create a document library.
a) Select File, Macros, Macro Library Manager...

b) Select the radio button Document Libraries, type the name of the new Macro MyFirstMac-
ro and click New.

c) Select Close.
STEP 3: Load the Macro Library "My first macro".
a) Select File, Macros, Load Macro Library

VBA TUTORIAL

5
b) Select the radio button Document Libraries, select MyFirstMacro and select Load.

STEP 4: To edit the macro, select File, Macros, Macro Editor.
+
The Macro Editor is opened:

The Macro Editor is used for:
Writing your code.
Designing your own forms. A form is something like this:
VBA TUTORIAL

6

Managing your macro library.
Compiling the code: it checks if you syntax is correct. The syntax is the grammar and
spelling of your code.
1.3. THE VBA HIERARCHY
A VBA program is a collection of lines of instruction code for the computer, hierarchically structured.
The Macro Library can contain one or more modules and forms. The modules can contain Sub Proce-
dures and Functions. The Sub Procedures and Functions contain the code, which is a set of instruc-
tions.

We will discuss the use of Sub Procedures.
VBA TUTORIAL

7
1.4. PROGRAMMING ESSENTIALS
1.4.1. THE SUB PROCEDURE
STEP 1: Make your first sub procedure. Copy and paste the code to your Macro Editor.
1 Sub PM_MyFirstSub
MsgBox ("Hello World")
End Sub
2
3
It should look like this:

EXPLANATION:
Your procedure needs a name. The following rules apply to all names in VBA:
Names must begin with a letter. After that, numbers are allowed.
No spaces.
No special characters, although _ is allowed.
If you start the name with PM_, the procedure will appear in the menu Tools, Run Macro.
PM stands for Pythagoras Macro.

VBA TUTORIAL

8
Msgbox is a built-in function. It displays a handy dialog box (the messagebox) containing a
message. Buttons, a title and an icon are optional. More about them in 1.4.6.

VBA is case-insensitive. This means that Msgbox is the same as msgbox, MSGBOX and
msgBoX. All cases used in the code are to improve readability.

STEP 2: Compile your code. Select Run, Compile or press F1. Your code must always be compiled be-
fore it can be used.
STEP 3: Return to your drawing.
STEP 4: Select Tools, Run Macro, MyFirstSub. The code in the sub procedure MyFirstSub will be run.
STEP 5: The messagebox appears. Select OK.
1.4.2. VARIABLES
GENERAL:
Variables are dataholders which are used to store information (data). We call this variables, since
the information can change. Since a computer has limited storage space (the RAM memory), we al-
ways will try to define our dataholder as specific as possible, and thus reducing storage space usage.
These are the most used Data Types:
DATA TYPES EXPLANATION EXAMPLE
Numbers
Integer
A (small) whole
number
Counting the text objects. E.g. 100 text ob-
jects.
Range: -32 768 to 32 767.
Long
A (big) whole
number
Counting the polygons in your drawing. E.g.
253 1532 polygons.
Range: 2 147 483 648 to 2 147 483 647
Double A decimal num- Coordinates of a point. X = 186 156.364, Y =
VBA TUTORIAL

9
ber 201 365.365
Text String Text characters
The name of your drawing.
Text that appears in a MessageBox.
True/False Boolean
Logical True or
False
Testing whether a condition is true or false.
Is the current temperature bigger than 25?
If yes, the test returns a logical True. If not,
the test returns a logical False.
This is a summary of the most used data types, for a complete overview check this site.
EXAMPLE:
1 Sub PM_MyFirstSub
Dim Number As Integer
Dim Sum As Integer
Number = 500
MsgBox(Number)
Sum = Number + 10
MsgBox (Sum)
End Sub
2
3
4
5
6
7
EXPLANATION:
The computer reads the code from top to bottom.
Line 2: You start with the Dim-statement. With this statement, you make a reservation of
storage space for the variable with the name Number. You create a dataholder with the
name Number. You also specify the Data Type, namely an Integer Data Type. Immediate-
ly after creating the dataholder, it contains no data. The dataholder is empty. When talking
about numbers, empty means 0.
Line 3: We are assigning a value to the variable Number. From that moment on, the stor-
age space of the variable Number contains 500.
Line 6: we are calculating the value of the variable Sum. Since Number = 500 from be-
fore, the value of Sum will be 500+10, which is 510.
It will happen often that you have to recalculate the value of a variable. Instead of line 6, we
could re-use the variable Number:
Number = Number +10
The general form of an assignment in that case is:
New Value of Variable = Operation(OldValue of Variable)
Math in VBA:
VBA TUTORIAL

10
+ Addition
- Subtraction
* Multiplication
/ Division
( ) Parentheses
^ Exponentiation
1.4.3. IFTHENELSE
Often we want our code to make a decision whether a condition is met or not. In that case, we use
the if-statement. In order to make decisions, we need to use conditional operators together with
the If control structure.
A. EXAMPLE:
1 Sub PM_TestingIfThenElse
Dim Number As Integer
Number = Inputbox (Give a number:)
If Number > 500 Then
MsgBox (The number you gave is greater than 500.)
Else
MsgBox (The number you gave is less than 500.)
End If
End Sub
2
3
4
5
6
7
8
9
B. EXPLANATION:
Line 3: InputBox is a built-in function, similar to MsgBox. It displays a simple dialog box
that asks the user for some input. The function returns whatever the user enters into the dia-
log box.

After entering a number (e.g. 100) in the dialog box and pressing OK, the value entered will
be stored into the variable Number.
VBA TUTORIAL

11
Line 4: since Number = 100, the If-statement checks if 100 is bigger than 500. This gives
the result FALSE, so the computer will immediately jump to the Else-part, skipping the code
after Then. Similar, if Number = 600, the code after Then will be executed. After that,
the computer will skip the Else-part and go straight to End If.
The > is a conditional operator. Other conditional operators are:
Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to
More about logical operators in 1.5.2.
We are not checking if the users input is correct.
C. GENERAL:
The syntaxis of the If-statement:
If condition Then
Code
Else
Code
End If
The code can contain multiple lines.
Condition is a test, which returns True or False. Its the first thing the computer evaluates.
If the condition is True (for example Number = 600), the test is passed, the code right after
THEN is executed.
If the condition is False (for example Number =200), the test failed and the code right after
ELSE is executed.
D. ADDITIONAL
For more complex programming, you can embed an IF-THEN-ELSE-statement into another
one. This is called nesting. An example:
Sub PM_TestingNestedIf
Dim Number As Integer
Number = Inputbox (Give a number:)
VBA TUTORIAL

12
If Number >= 0 Then
If Number >= 1000 Then
MsgBox (The number you gave is positive and >= 1000.)
Else
MsgBox (The number you gave is positive and < 1000.)
End If
Else
MsgBox (The number you gave is negative.)
End If
End Sub
1.4.4. FORNEXT
Sometimes you want a piece of code to be repeated a specified amount of times (in a loop). In that
case you need the FOR-NEXT-statement.
A. EXAMPLE:
1 Sub PM_TestingForNextLoop

Dim Counter As Integer
Dim Result As Integer
For Counter = 1 To 10
Result = 3 * Counter
Msgbox (Result)
Next Counter
End Sub
2
3
4
5
6
7
8
9
10
B. EXPLANATION:
When the FOR-loop starts, VBA evaluates where the loop begins, and where it ends. The FOR-
loop takes 1 as step. What does this mean?
When running the code, the computer arrives at the FOR-statement. The loop starts with the
value of Counter = 1, and the computer runs the code between FOR and NEXT. It then calcu-
lates Result = 3 * 1 = 3. It then displays the variable Result in a MessageBox. The code
then arrives at NEXT. The computer raises the value of Counter by 1, resulting in Counter =
2. It then checks if the value of Counter > 10. If not, it reruns the code between FOR and
NEXT. It recalculates the value of Result. Since Counter = 2, Result = 3*2 = 6. The
MessageBox then displays 6. The computer then arrives at NEXT, so he raises the value of
Counter by 1, resulting in Counter = 3, again checking if Counter > 10, and so on.
VBA TUTORIAL

13
When arriving for the 10th time at the end of the loop, with Counter = 10, the value of
Counter is increased by 1, resulting in Counter = 11. It restarts at the beginning, but now
Counter is bigger then 10, so the loop ends. The computer then jumps to the next line after the
FOR-NEXT-loop.
C. GENERAL:
The Syntaxis of the For-Next statement is:
For Counter = BeginValue To EndValue [Step Value]
Code
Next Counter
The square parentheses [ ] mean that its optional. If you dont mention this, the value of Counter
will be raised by 1.
Sub PM_TestingForNextLoop

Dim Counter As Integer

For Counter = 10 To 0 Step -2
MsgBox (Counter)
Next Counter

End Sub
D. ADDITIONAL
Again, it is possible to nest FOR-loops into each other, and combine it with the IF-THEN-ELSE-
statements.
You can improve the readability of the code by using indents:
Sub PM_TestingForNextLoop

Dim Counter1 As Integer
Dim Counter2 As Integer
Dim Result As Integer

For Counter1 = 10 To 12
For Counter2 = 2 To 4
Result = Counter1*Counter2
If Result <= 40 Then
MsgBox (Result)
End If
Next Counter2
Next Counter1

VBA TUTORIAL

14
End Sub
Is more readible than:
Sub PM_TestingForNextLoop

Dim Counter1 As Integer
Dim Counter2 As Integer
Dim Result As Integer

For Counter1 = 10 To 12
For Counter2 = 2 To 4
Result = Counter1*Counter2
If Result <= 40 Then
MsgBox (Result)
End If
Next Counter2
Next Counter1

End Sub
1.4.5. DO WHILELOOP
When you want a piece of code to be repeated, but you dont know how much in advance, you use
DO WHILELOOP.
A. EXAMPLE:
Sub PM_TestDoWhileLoop1
Dim Number As Long

Do While Number<500
Number = InputBox("Give a number:")
Loop

End Sub
B. EXPLANATION:
The loop will be repeated as long as the given number is bigger than 500.
If you press Cancel, an error raises. This can be solved by:
Sub PM_TestDoWhileLoop2
Dim Number As Long

Do While Number<500
Number = InputBox("Give a number:")
If Number = vbCancel Then
VBA TUTORIAL

15
Exit Do
End If
Loop

End Sub
With Exit Do, you can exit the loop
C. GENERAL:
Do While condition
Code
Loop
Or:
Do
Code
Loop While condition
1.4.6. FUNCTIONS
We already used two functions: MessageBox and InputBox. We can do a lot more with them then we
already did.
What is a function? The definition says that the main purpose of a function is to accept a certain in-
put and return a value which is passed on to the main program to finish the execution.
There are two types of functions: the built-in-ones and the ones created by programmers. We will
only discuss the first kind.
A. MESSAGEBOX
MsgBox displays a message, but it also lets you know which of two or more
buttons the user clicked. The syntax is:
ReturnValue=MsgBox(Prompt[, Style Value] [, Title])
The first argument, Prompt, will display the message in the message box.
The second (optional) argument Style Value will determine what type of command buttons
appear on the message box.
VBA TUTORIAL

16
Style Value Named Constant Buttons Displayed
0 vbOkOnly

1 vbOkCancel

2 vbAbortRetryIgnore

3 vbYesNoCancel

4 vbYesNo

5 vbRetryCancel

The third (optional) argument Title will display the title of the message board.
You want to know which button the user pressed. This button is stored into the variable Re-
turnValue. When asking for a ReturnValue, the parentheses are required. When not asking
for a ReturnValue, like we did before, no parentheses are required.
An example:
Sub PM_TestingMessagebox

Dim ReturnValue As Integer

ReturnValue = MsgBox("Press Yes, No or Cancel", _
vbYesNoCancel, "Title of the messagebox")

If ReturnValue = vbYes Then
MsgBox "You have pressed Yes"
Else
If Returnvalue = vbNo Then
MsgBox "You have pressed No"
Else
MsgBox "You have pressed Cancel"
End If
End If

End Sub
You might be confused by now on when to use parentheses and when not. When working
with a ReturnValue, you have to use parentheses. Otherwise, not.
When adding an underscore _ at the end of a line, the statement continues onto the next
line.
The MessageBox is a useful function to check for errors when you are coding. Afterwards, de-
lete it, or place an apostrophe in front of the line, which makes it a comment.
VBA TUTORIAL

17
B. INPUTBOX
The Inputbox-function displays a message and a
text box where the user can type a response.
The syntax is:
ReturnValue = InputBox(Prompt [, Title] [, Default])
The arguments Prompt and Title are similar to the Messagebox Function.
The third argument, Default, allows you to have a default value already filled in.

An example:
Sub PM_TestingInputBox
Dim Land As String
Land = InputBox("In what country are you born? ", _
"Birth", "Belgium")
End Sub
1.5. MORE VBA
1.5.1. COMMENTS
To add an explanation in your code, type an apostrophe . Everything to the right of the will be ig-
nored by VBA.
Sub PM_TestingComment
This is comment, ignored by VBA
Dim Number As Integer this is also comment
End Sub
An apostrophe is also an excellent way to take a line of code off active duty without deleting them
for good. This can come in handy when you are trying two different approaches.
1.5.2. LOGICAL OPERATORS
Sometimes we need to combine the evaluation of two expressions before we can continue.
VBA TUTORIAL

18
Operator Meaning
And Both expressions must be true
Or One of two expressions must be true
Not Negates the expression
EXAMPLE:
Sub PM_AndTest

Dim Number As String
Dim Age As String

Number = InputBox("Give a number:")
Age = InputBox("Give your age:")

If Number > 100 And Age < 12 Then
MsgBox ("Congratulations! You won a price!")
Else
MsgBox ("Sorry, you didn't win any price.")
End If

End Sub
An example of NOT can be found in 1.5.4.
1.5.3. BASIC STRING HANDLING
A. ADDING STRINGS TOGETHER WITH &
Sometimes you will want to glue two or more strings together. You can do this using the amper-
sand &.
EXAMPLE:
Sub PM_AddingStringsTogether

Dim String1 As String
Dim String2 As String
Dim String3 As String

String1 = InputBox("Give your first name:")
String2 = InputBox("Give your last name:")

String3 = String1 & " " & String2

MsgBox ("Your full name is: " & String3)
VBA TUTORIAL

19

End Sub
B. NEWLINE
A new line in your string is a non-visible character, which you cant type in your code. To add this, use
vbCrLf. To add a tab character, use vbTab.
EXAMPLE:
Sub PM_TestNewLine

Dim String1 As String
Dim String2 As String

String1 = InputBox("Give your first name:")
String2 = InputBox("Give your last name:")

MsgBox ("Your first name is: " & String1 & vbCrLf & "Your last name
is: " & String2)

End Sub
1.5.4. ISNUMERIC()
A common used code to check if your user input is a number:
Sub PM_CheckingUserInput
Dim Number As String
Do
Number = InputBox(Give a number:)
Loop While Not(Isnumeric(Number))
End Sub
The function Isnumeric() checks whether the string is a number or not. It returns True
or False.
For example, if you type text in the inputbox, Isnumeric(text) will return False.
The function Not() reverses the outcome of the inner function. So if Isnumeric() re-
turns False, Not(False) will return True, and the other way around.
1.5.5. DECIMAL SEPERATOR
The decimal separator in VBA is always a point, regardless of your settings in Pythagoras. This in-
volves the following situations:
VBA TUTORIAL

20
Output in a MessageBox or a form.
Input in a InputBox or a form.
Doing a calculation with a decimal number in the code.

1.5.6. TOPICS TO CHECK OUT YOURSELF
As we said before, this tutorial is to get you started. For a more thorough knowledge, these topics
are a good place to start. Click on the item for the webpage.
Arrays
String manipulation
Select Case
Do Loop
While End Loop
Functions/Procedures
Scope of variables
VBA TUTORIAL

21
2. VBA FOR PYTHAGORAS
We are going to work with a Pythagoras drawing, so a general knowledge of Pythagoras Objects,
such as Lines, Points, Sheets, Symbols, is required.
2.1. THE PYTHAGORAS OBJECT MODEL
2.1.1. IN GENERAL
To understand object-oriented programming, objects are the key. Whats an object? Like real-life
objects, they have states (properties) and behaviour (methods). A bike can have properties like col-
or, current gear and current speed and behaviour like changing gear and applying brakes. The
property current gear can be changed by using the method changing gear.
For example, a Pythagoras Document can have the property Name, which is untitled 1.pyt. You can
change its coordinate system by using the method SetCoordinateReferenceSystem.
2.1.2. HIERARCHY OF THE PYTHAGORAS OBJECT MODEL
All objects exist in a hierarchy in which one type of object contains objects of other types. For exam-
ple, the Pythagoras Application has 2 drawings opened. One drawing has the Overlay Drawing active.
There are 2 types of Overlay: the Drawing (Local) or the Paper (the sheet). The overlay can contain
lines, points and images,.

VBA TUTORIAL

22
2.1.3. USING THE VBA MANUAL
A complete overview of all objects with their properties and methods and how to use them, can be
found in the VBA Manual on the Pythagoras website. Click here for the link.
2.2. VBA FOR PYTHAGORAS IN PRACTICE
2.2.1. EXAMPLE 1: CHANGE COMMENT
Macro description: The user can change the comment-field of object(s). The user first selects one or
more objects. Then the macro is started. The macro asks via an InputBox what the new comment is.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Sub PM_Example1

Dim App As Application
Dim Doc As Document
Dim SelectedObjects As Selection
Dim Object As CADObject
Dim NewComment As String

Ask the user the new comment:
NewComment = InputBox("New Comment: ", "Add Comment")

Go down the hierarchy to access the selected objects:
Set App = New Application
App.GetActiveDocument Doc
Doc.GetSelection SelectedObjects
SelectedObjects.GetFirst ptAll, Object

Looping through all objects:
Do While(Not(Object Is Nothing))
Object.Comment = NewComment
SelectedObjects.GetNext Object
Loop

End Sub
Line 10 asks the users input, the new comment which has to be added to the selected ob-
jects.
With the Pythagoras Object Model in mind, we will look at Lines 13-16.
The Application object is the top-level object. To use the properties and meth-
ods of Application, an object of that kind has to be created.
VBA TUTORIAL

23
Going down the hierarchy, we are extracting the active document (= the currently
used document) from the object App and put this active document in the variable
Doc. We are using the method GetActiveDocument.
Going further down the hierarchy, we are extracting the selected objects from the
active document Doc and put the selected objects in the variable
SelectedObjects. We are using the method GetSelection.
Continuing going down the hierarchy, we are extracting the first object from
SelectedObjects and put this object in the variable Object. We are using the
method GetFirst:

Types: these are Pythagoras constants, referring to types of objects. Possible types
are: ptAll, ptPoint, ptLine, ptArc, ptClothoid, ptText,
ptRichText, ptImage, ptCurve, ptPath, ptPolygon,
ptCircle, ptCoordinateSystem, ptCompound.
When choosing ptAll as parameter, all types of objects are extracted from
SelectedObjects. If you would just need the Polygons from your selection, the
parameter would be ptPolygon. If you want the points and the lines from your se-
lection, your parameter would be ptPoint+ptLine.
If the selection is empty, or there are no objects of the type that you have specified,
the variable Object will be nothing. We say Object Is Nothing.
Line 19-22:
We will only enter the do loop if the variable Object is not empty. If we dont check
this, an VBA runtime error will raise with the next line of code, because we cant
change the objects comment when there is no object.
When first entering the DO-loop, the first objects comment is altered to the value of
NewComment.
After that, the next object is extracted from the selection.

VBA TUTORIAL

24
The loop is repeated until there is no Object left in the selection.
2.2.2. EXAMPLE 2: AVERAGE POINT
Macro description: The user can select 2 or more points. The average point is calculated, which is the
average of each coordinate separately. This point is drawn on the screen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Sub PM_AveragePoint

Dim App As Application
Dim Doc As Document
Dim Drawing As Overlay
Dim SelectedObjects As Selection
Dim Object As CADObject
Dim P As Point
Dim AveragePoint As Point
Dim Coord As XYZ
Dim Xcoordinats As Double
Dim Ycoordinats As Double
Dim Zcoordinats As Double
Dim AverageCoordinates As XYZ
Dim NumberOfPoints As Integer

Set App = New Application
App.GetActiveDocument Doc
Doc.GetSelection SelectedObjects

If SelectedObjects.NrOfObjects > 1 Then check if the user
has selected at
least 2 points

SelectedObjects.GetFirst ptPoint, Object

Loop through all selected objects:
Do While(Not(Object Is Nothing))
Object.GetPoint P
Coord = P.Coordinates

Store coordinates of the selected point in
variable Xcoordinats (Y-Z)
Xcoordinats = Xcoordinats + Coord.X
Ycoordinats = Ycoordinats + Coord.Y
Zcoordinats = Zcoordinats + Coord.Z

NumberOfPoints = NumberOfPoints + 1

SelectedObjects.GetNext Object
Loop

Calculate the average of X, Y and Z
AverageCoordinates.X = XCoordinats/NumberOfPoints
VBA TUTORIAL

25
45
46
47
48
49
50
51
52
53
54
55
56
57
58
AverageCoordinates.Y = YCoordinats/NumberOfPoints
AverageCoordinates.Z = ZCoordinats/NumberOfPoints

Go down the hierarchy of the object model
To access the drawing overlay, on which we can
place a new point:
Doc.GetOverlay ptDrawing, Drawing
Drawing.CreatePoint AverageCoordinates, AveragePoint
AveragePoint.Color = ptRed
Else
MsgBox ("Select at least two points!")
End If

End Sub
Line 21: we are checking if the user has selected more than one object. If not, the code is
skipped and the ELSE-part is executed, where a Messagebox will display.
Line 29: since we want to use the properties of the point, we first need to convert the gen-
eral CADObject to the more specific Point Object.
Note: a lot of the properties of the general CADObject and a Point are in common (like Com-
ment, Color,). A conversion is only necessary when you need specific properties of the
point.
Line 30: we are putting the coordinates of the Point, which is a property, into the variable
Coord. We need this to do our calculations of the average. The variable Coord is a special
Pythagoras Data Type: XYZ. In this data type, the X, Y and Z coordinates are stored as dou-
bles. Look at page 117-1 in the VBA Manual for a description.
Lets say we select 2 points. Point 1 has coordinates (10,10,0) and Point 2 has coordinates
(20,20,20). To calculate the average of the X-coordinates, we need to add all X-coordinates,
and divide them with the total number of points. On line 34-36, we are doing the addition of
the coordinates. To calculate the total number of points, we use a variable
NumberOfPoints.
When we first enter the DO-WHILE-LOOP, the value of variable Xcoordinat is 0, because
when we declare the variable, the value is 0. So we add the value X-coordinat of the first se-
lected point to the variable Xcoordinat. The variable Xcoordinat will be 10. When we
enter the loop for the second time, we are recalculating the variable Xcoordinat. We are
adding the X-coordinat of the second point to the variable Xcoordinat. So the variable
Xcoordinat = 10 + 20 = 30. When we exit the loop (after having looped 2 times), the vari-
able NumberOfPoints is 2. So the average is 30/2 = 15.
Line 42-44: we want to add this new point to the drawing. We need to define whether we
want it on the Paper Overlay or the Drawing Overlay. Since we are doing everything on the
VBA TUTORIAL

26
drawing overlay, we need to extract this from the active document using
Doc.Getoverlay:

On the drawing overlay, we want to create a point using the method CreatePoint:

The second parameter P As Point can be used to change settings of the created point
after it is created. We will turn the color into red using the property Color. The standard
colors are Pythagoras Constants (Manual chapter 118).
2.2.3. EXAMPLE 3: USING THE PRIVATETOOL
In example 2 and 3, we expect from the user to have selected a number of objects before the macro
starts. When the Private Tool Mode is active, a macro is started when a mouse event happens. A
mouse event can be a click with the mouse, a double-click, a right click,. The full list can be found in
the manual page 1-7.
Macro description: After the macro is started, the user can select a line. The macro changes the color
of the selected line into Blue, its layer is changed into the layer New Layer.
1
2
3
4
5
6
7
8
9
10
11
12
Sub PM_ChangeLine

Dim App As Application

Set App = New Application

App.PrivateToolSelected = True
App.PrivateToolSnapping = ptLine

End Sub

==============================================================
VBA TUTORIAL

27
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
This is the mouse-event sub:

Sub OnMouseDown

Dim App As Application
Dim Doc As Document
Dim Obj As CADObject
Dim P As Point

Set App = New Application
App.GetActiveDocument Doc

Doc.GetObjectUnderCursor ptLine, Obj

If Not(Obj Is Nothing) Then check if the user has selected
a line
Obj.Color = ptBlue
Obj.Layer = "New Layer"

Else
MsgBox ("Please select a line.")
End If

End Sub
In the sub procedure PM_ChangeLine, the Private Tool Mode is activated.
While Private Tool Mode is active, and you click with your mouse somewhere in your draw-
ing, the code of the sub procedure OnMouseDown is executed.
Line 25: since you need the object (the line) you just clicked on, we are using the method
GetObjectUnderCursor. The object is stored into the variable Obj.
Line 27: we are checking if the user has clicked on a line. Otherwise, if the user clicks on an
empty space of the drawing, the macro will produce its own error message.
2.3. MAKING LARGER PROJECTS
2.3.1. SUB ONSTARTUP
If your macro contains a sub procedure named OnStartUp, the code inside this sub procedure will be
executed when the macro is loaded. This feature can be used to load your own user menu. If you
combine this with setting your macro as Startup Library, you can personalize the default environment
of Pythagoras at startup.
VBA TUTORIAL

28

Example of your own user menu:
Sub OnStartUp

Dim App As Application

Set App = New Application

App.NewUserMenu "MyMenu"
App.AppendUserMenuItem "MenuItem1", True, False, "MacroName1", 1
App.AppendUserMenuItem "MenuItem2", True, False, "MacroName2", 2

End Sub

Sub MacroName1

MsgBox ("The code of Sub MacroName1 is now executed")

End Sub

Sub MacroName2

MsgBox ("The code of Sub MacroName2 is now executed")

End Sub
This will result in:

You can find the methods about menu items in the manual page 2-9.
VBA TUTORIAL

29

2.3.2. MANAGING YOUR MODULES AND FORMS
When projects get bigger and the sub procedures keep piling up, one module wont be enough. You
can place your sub procedures in different modules. An example of the Bonus Tools macro:

You can manage your modules and forms using the Module Manager in the VBA Editor:



VBA TUTORIAL

30
2.4. THE END
We have reached the end of this tutorial. A few tips to end with:
Check out the Bonus Tools. These macros are made by Pythagoras to show the strength and
possibilities of VBA. It is a collection of both easy and complex macros. You can learn from
the code, or use parts of it.
Programming your own macros is a process of trial and error. You will get stuck sometimes.
Dont give up too easily. Overthink the problem youre having and check the internet for so-
lutions. Also, the support team of Pythagoras can be reached by mail: sup-
port@pythagoras.net.

Good luck!

You might also like