Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
VBA TUTORIAL
TABLE OF CONTENTS
1. VBA GENERAL ............................................................................................................................... 3 1.1. 1.2. 1.3. 1.4. Introduction ............................................................................................................................. 3 Getting Started ........................................................................................................................ 3 The VBA Hierarchy ................................................................................................................... 6 Programming essentials .......................................................................................................... 7 The Sub Procedure .......................................................................................................... 7 Variables .......................................................................................................................... 8 IfThenElse ................................................................................................................. 10 Fornext ........................................................................................................................ 12 Do whileloop ............................................................................................................... 14 Functions ....................................................................................................................... 15
More VBA .............................................................................................................................. 17 Comments ..................................................................................................................... 17 Logical operators ........................................................................................................... 17 Basic string handling ...................................................................................................... 18 IsNumeric() .................................................................................................................... 19 Decimal seperator ......................................................................................................... 19 Topics to check out yourself .......................................................................................... 20
VBA for Pythagoras........................................................................................................................ 21 2.1. The Pythagoras Object Model ............................................................................................... 21 In general ....................................................................................................................... 21 Hierarchy of the pythagoras object model.................................................................... 21 Using the VBA manual ................................................................................................... 22
VBA for Pythagoras in practice .............................................................................................. 22 Example 1: Change comment ........................................................................................ 22 Example 2: Average point.............................................................................................. 24 Example 3: Using the PrivateTool .................................................................................. 26
Making Larger projects .......................................................................................................... 27 Sub OnStartUp ............................................................................................................... 27 Managing your modules and forms .............................................................................. 29
VBA TUTORIAL
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 Microsoft 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 Pythagoras. 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
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 MyFirstMacro and click New.
c) Select Close. STEP 3: Load the Macro Library "My first macro". a) Select File, Macros, Load Macro Library
VBA TUTORIAL
b) Select the radio button Document Libraries, select MyFirstMacro and select Load.
The Macro Editor is used for: Writing your code. Designing your own forms. A form is something like this:
VBA TUTORIAL
Managing your macro library. Compiling the code: it checks if you syntax is correct. The syntax is the grammar and spelling of your code.
VBA TUTORIAL
1.4.PROGRAMMING ESSENTIALS
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
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 before 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 always 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 A (small) whole number EXAMPLE Counting the text objects. E.g. 100 text objects. Range: -32 768 to 32 767. Counting the polygons in your drawing. E.g. 253 1532 polygons. Range: 2 147 483 648 to 2 147 483 647 Coordinates of a point. X = 186 156.364, Y =
Integer
Numbers Long
Double
VBA TUTORIAL
201 365.365 The name of your drawing. Text that appears in a MessageBox. Testing whether a condition is true or false.
True/False
Boolean
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 2 Dim Sum As Integer 3 Number = 500 4 MsgBox(Number) 5 Sum = Number + 10 6 MsgBox (Sum) 7 End Sub 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. Immediately 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 storage space of the variable Number contains 500. Line 6: we are calculating the value of the variable Sum. Since Number = 500 from before, 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
+ * / () ^
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 2 3 4 5 6 7 8 9 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 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 dialog 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.
10
VBA TUTORIAL
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 = > < >= <= <> 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:) Meaning Equal to More than Less Than More than and equal Less than and equal Not Equal to
11
VBA TUTORIAL
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 2 3 4 5 6 7 8 9 10 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
B. EXPLANATION: When the FOR-loop starts, VBA evaluates where the loop begins, and where it ends. The FORloop 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 calculates 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.
12
VBA TUTORIAL
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-ELSEstatements. 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
13
VBA TUTORIAL
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
14
VBA TUTORIAL
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 input 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.
15
VBA TUTORIAL
Style Value 0 1 2 3 4 5
Buttons Displayed
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 ReturnValue. 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, delete it, or place an apostrophe in front of the line, which makes it a comment.
16
VBA TUTORIAL
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 ignored 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.
17
VBA TUTORIAL
Operator And Or Not EXAMPLE: Sub PM_AndTest Dim Number As String Dim Age As String Number = InputBox("Give a number:") Age = InputBox("Give your age:")
Meaning Both expressions must be true One of two expressions must be true Negates the expression
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.
18
VBA TUTORIAL
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() returns False, Not(False) will return True, and the other way around.
19
VBA TUTORIAL
Output in a MessageBox or a form. Input in a InputBox or a form. Doing a calculation with a decimal number in the code.
20
VBA TUTORIAL
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 color, 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.
21
VBA TUTORIAL
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 o bjects. 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 methods of Application, an object of that kind has to be created.
22
VBA TUTORIAL
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, ptRichText, ptPoint, ptLine, ptArc, ptClothoid, ptPath, ptText,
ptImage,
ptCurve,
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 selection, 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.
23
VBA TUTORIAL
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
24
VBA TUTORIAL
45 AverageCoordinates.Y = YCoordinats/NumberOfPoints 46 AverageCoordinates.Z = ZCoordinats/NumberOfPoints 47 48 Go down the hierarchy of the object model 49 To access the drawing overlay, on which we can 50 place a new point: 51 Doc.GetOverlay ptDrawing, Drawing 52 Drawing.CreatePoint AverageCoordinates, AveragePoint 53 AveragePoint.Color = ptRed 54 Else 55 MsgBox ("Select at least two points!") 56 End If 57 58 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 general CADObject to the more specific Point Object. Note: a lot of the properties of the general CADObject and a Point are in common (like Comment, 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 doubles. 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 selected 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 variable 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
25
VBA TUTORIAL
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).
Set App = New Application App.PrivateToolSelected = True App.PrivateToolSnapping = ptLine End Sub ==============================================================
26
VBA TUTORIAL
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 Dim Dim Dim App Doc Obj P As As As As Application Document CADObject Point
Set App = New Application App.GetActiveDocument Doc Doc.GetObjectUnderCursor ptLine, Obj If Not(Obj Is Nothing) Then 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 drawing, 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. check if the user has selected a line
27
VBA TUTORIAL
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.
28
VBA TUTORIAL
You can manage your modules and forms using the Module Manager in the VBA Editor:
29
VBA TUTORIAL
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 solutions. Also, the support team of Pythagoras can be reached by mail: sup-
port@pythagoras.net.
Good luck!
30