Professional Documents
Culture Documents
Script
(Book of Examples)
2011
University of Duisburg-Essen
Faculty of Engineering
Department of Civil Engineering
Structural Analysis and Construction
Dr. E. Baeck
18.4.2011
Contents
I Introduction to VBA 1
1 General Statements 2
1.1 AutoCad - Versions and VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 VB-IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Macro Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Basics in VBA 5
2.1 Data Types, Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.1 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.2 Declaration of Variables and Constants in VBA . . . . . . . . . . . . . . . 6
2.1.2.1 Explicit Declarations . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1.2.2 Implicit Declarations . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.1 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.2 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.3 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Assigning Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4 FOR-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6 Calculation of Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.7 Newton Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.7.1 Pure VBA Version with Smart Slope . . . . . . . . . . . . . . . . . . . . . 15
2.7.2 EXCEL VBA Version with EXCEL-Sheet-GUI . . . . . . . . . . . . . . . 18
2.8 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.9 Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.10 Class Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.10.1 A Mass Point Class Module . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.10.2 Create and Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
II AutoCAD-Objects 36
iii
Page iv CAD in Civil Engineering / 2011
5 Primitives in Modelspace 45
5.1 AcadLine Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.2 Delete Objects from ModelSpace . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3 AcadSphere Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
6 Random Masspoints 52
6.1 Class Modul Mass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6.1.1 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6.1.2 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
6.2 Class Modul Masses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2.1 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2.2 Methodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.3 Frame Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.3.1 EXCEL-Sheet, Input Section . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.3.2 EXCEL-Sheet, Output Section . . . . . . . . . . . . . . . . . . . . . . . . 58
6.3.3 Sample, Step 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.3.4 Sample, Step 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
IV Exercises 66
E. Baeck
Part I
Introduction to VBA
1
1
General Statements
If you want to write VBA extensions to the AutoCad application, you have to install an
addon, if you use an AutoCAD version 2010 and higher. The addon has to be selected from the
AutoCAD service download page1 for the used AutoCAD version and the applied platform.
Figure 1.1 shows the download page for the VBA development extension.
Within a first step the self extracting archive file is executed. All files of the setup are stored in
a work folder. The setup application is started automatically and the VBA extension will be
installed. After the installation the steps of the following sections can be executed.
1.2 VB-IDE
2
1.3. MACRO MANAGER Page 3
The Macro-Manager (figure 1.2) can be started with the command vbarun. A macro (vba
script) can be started with the methode Ausführen. The command Bearbeiten starts the
VBA-IDE. The command VBA-Manager starts the VBA-Manager (see figure 1.3).
VBA scripts or macros live in modules of a AutoCAD project. An AutoCAD project is stored
in an dvb-file. With the command Laden a dvb-file is loaded. The methode Makros returns
to the Makro Manager (see above). A new project is created by the methode Neu and saved
to the disc by the methode Speichern unter.
18.4.2011
Page 4 CAD in Civil Engineering / 2011
E. Baeck
2
Basics in VBA
Within the following section we will discuss the available data types for the variables of VBA.
We will discuss how to declare and initialize variables and constants.
5
Page 6 CAD in Civil Engineering / 2011
A constant is simple declared by the key word const. The following example shows the decla-
ration of two integer constants and one string constant. An error occur, if you try to assign a
value to a constant.
Const A = 1
Const B = 2
Const N = "Harry"
An explicit declaration of a variable is set with the key word Dim and As. Dim is followed by
the variables name. After the variable’s name the data type is set after the key word As.
Dim A As Integer
Dim B As Integer
Dim N As String
You need not declare the constants and variables in a header section of a block of code like in
C. In VBA declarations can be used like in C++ in any position of the code.
An explicit declaration can be forced by the statement option explicit. If so, this statement
should be the first statement within the VBA module. If option explicit is set, the use of
not explicit declared variables causes a runtime error.
If option explicit is not set and a variable is introduced in a statement at the left side of
the assign operator, VBA allocates a variable of the type variant. That means, that VBA
creates a container for everything. So we can assign every data type to a variant variable. The
variant data type especially is used as interface data type to the EXCEL application within
a call of user functions.
If a special data type should be used implementing a variable, the variables name can be used
like in the FORTRAN language. In VBA we can extend the variables name by a character,
which sets up the variables data type. The following declarations are available (see table 2.2).
E. Baeck
2.2. OPERATORS Page 7
2.2 Operators
VBA offers a set of operators, which are offered from the most computer languages. VBA
uses the same precedence as we know form the mathematics. The power operation has the
strongest binding followed by the point operators (products and divisions) followed by the line
operators (plus and minus). Unary operators will always be applied first. To change the standard
precedence of the operators we use like in mathematics parenthesis to dictate the way a formula
should be evaluated.
Unary operators are working only on one value, therefor unary. In VBA there are the following
unary operators available.
VBA offers the following arithmetic operators. You should be careful with the usage of data
types especially within divisions. If you use integers, the result generally will be truncated.
Boolean operators are used to branch and to make decisions. The comparing operators of VBA
are now nearly identical to the C comparing operators.
18.4.2011
Page 8 CAD in Civil Engineering / 2011
The result of a boolean expression like above are the boolean values False or True. To combine
comparing expressions the following logical operators can be used.1
1
To make expressions clear parenthesis should be used. A term within a parenthesis is evaluated first and it’s
result then is used in further evaluations outside the parenthesis. With parenthesis the order of the evaluation
can be set.
E. Baeck
2.3. ASSIGNING VALUES Page 9
Assigning a value to a variable is done with the operator =. Dump output for program testing
is written in the immediate window by the Debug object using the object method Print.
’ Example 1
’ Summing up 2 values and writing a log to the output window
Dim a As Integer
Dim b As Integer
a = 1
Debug.Print "a = " & a
b = 2
Debug.Print "b = " & b
a = a + b
Debug.Print "a = " & a
End Sub
End of Coding
18.4.2011
Page 10 CAD in Civil Engineering / 2011
2.4 FOR-Loops
The following example shows the usage of a for loop. A for -loop starts with the key word for
and ends with the key word next. A for loop needs a counter variable which is initialized by the
first value and runs up to the To-value under consideration of the step width.
’ Example 2
’ Summing up all odd integers from 1 to 10
’ Writing the log for i-Values graeter 5
Dim s As Integer
Dim i As Integer
s = 0
For i = 1 To 10 Step 2
s = s + i
If i > 5 Then
Debug.Print "i = " & i & " s = " & s
End If
Next
End Sub
End of Coding
E. Baeck
2.5. DATA TYPES Page 11
The next example shows the difference between several data types using them in the context of
a program which calculates the faculty. It can be easily shown that the use of double as data
type for the faculty is the best choice to avoid an overflow problem.
’ Example 3
’ Calculating the faculty for several data types
’ Dim f As integer
’ Dim f As long
’ Dim f as single
Dim f As Double
Dim i As Integer
Dim n As Integer
f = f * i
Debug.Print " i = " & i & " f = " & f
Next
End Sub
End of Coding
18.4.2011
Page 12 CAD in Civil Engineering / 2011
The following example shows the usage of an implicit do loop. The infinite loop ends with a
break condition witch checks the visibility of an -value in the numeric noise.
The input data are captured by the VBA input box function. The user can select single or
double as precision key. If a unknown key is given the function precision returns an error value.
The results are shown by a Message Box using the function MsgBox .
’ main-program of precision
pre = precision(key)
Debug.Print "precision = " & pre
End Sub
End of Coding
E. Baeck
2.6. CALCULATION OF PRECISION Page 13
To check the precision of a 4-byte (single) and a 8-byte floating point variable, we have to
introduce complete sets of variables with the desired data type, to produce correct precision
cutting.
If there is a iterative reduced -value added to the variable content of one, this -value vanishes
if the relative precision is reached. The step before -value vanishes gives the relative precision.
’ impclicit loop
Do
Debug.Print "x1s = " & x1s & ", epss = " & epss
’ check if eps still exists
If x1s = x2s Then Exit Do
Loop
18.4.2011
Page 14 CAD in Civil Engineering / 2011
End If
End Function
End of Coding
E. Baeck
2.7. NEWTON ALGORITHM Page 15
The following example implements the algorithm of newton to search the roots of a given func-
tion.
The only parameters, which are given by the user are the maximal number of iteration to avoid
an endless loop and the precision of the break condition.
The function newton returns the root value, if found. If an error happened the function will
return zero and will give an error flag of 1 or 2.
’ Newton algorithm
Sub example 5()
nmax = 20
nmax = InputBox("Maximum of iterations", "Input", nmax)
eps = 0.000001
x0 = newton(iter, nmax, eps, flag)
MsgBox "result = " & x0 & " (Iterations: " & iter & ")"
MsgBox "Error " & flag & ". No solution found (Iterations: " & iter & ")"
End If
End Sub
End of Coding
18.4.2011
Page 16 CAD in Civil Engineering / 2011
The user function should be implemented in the frame of the following function f.
f = x ^ 2 + 1
End Function
delx = 0.000001
End Function
’ Newton algorithm
Function newton(n As Integer, nmax As Integer, eps As Double, flag As Integer) As Double
Dim x As Double
Dim fx As Double ’ function value
Dim fsx As Double ’ slope of the function
Dim stp As Double ’ step in case of error 1
’ counter
n = 1
stp = 0.1
’ 0: solution found
flag = 0
’ iteration loop
Do
’ solution found
start:
fx = f(x)
fsx = fs(x)
E. Baeck
2.7. NEWTON ALGORITHM Page 17
’ debug information
Debug.Print " f(" & x & ")= " & fx & " fs(" & x & ")= " & fsx
’ f’(x) = 0 ?
If Abs(fsx) < eps Then
newton = 0
x = x + stp
End If
’ next x-value
x = x - fx / fsx
n = n + 1
Loop
End Function
End of Coding
18.4.2011
Page 18 CAD in Civil Engineering / 2011
The following version of newton implements the algorithm with an excel-sheet gui (see figure
2.1) . In the input section there are input cells for the initial value of x , the desired precision
and the maximum number of iterations hightligthed in yellow. Result information is printed in
the result cells highligthed in light blue. After execution of newton the root and the number
of performed iterations are printed. If newton dedectes problems the root result cell is used
for further informations.
The command button supports a click event. If the command button is clicked in layout mode,
a click event function frame is created called commandbutton1 click (see figure 2.2). This
function is call from EXCEL if the command button is clickt and the VB code of the function
is executed.
The event code of a sheets button lives in the sheets code file. To support a more general usable
newton function, the code of newton is set into a modul called newtonlib2 . The code in
newtonlib is designed without explicit links to excel specific features. So it’s possible to use
this code simply by copying it into other VBA driven applications like AutoCAD.
The event function for the command button is given by the following code.3
2
A new module can be inserted into the EXCEL project by use of the context menu of the project browser.
3
The object range of the EXCEL-type library can be used for VBA-EXCEL communication. It’s useful to
write data from VBA into an EXCEL-cell or to read data from an EXCEL-cell into a VBA variable.
E. Baeck
2.7. NEWTON ALGORITHM Page 19
’ loading data
x0 = Range("X 0")
eps = Range("Precision")
iterX = Range("MaxIter")
’ start calculation
’ - flag = 0: root found
’ = 1: vanishing slope
’ = 2: no root found
x0 = newton(x0, iterX, eps, flag, iter)
End If
18.4.2011
Page 20 CAD in Civil Engineering / 2011
End Sub
End of Coding
E. Baeck
2.7. NEWTON ALGORITHM Page 21
The code of the general newton functions is set into a module, which is called newtonlib.
Because the function newton should be callable from outside of the module, the function should
have the attribute public. All other functions, which are in this context private functions, that
means which are not called from outside, are set to private functions. To check the iteration
data, a debug.print command is set at the end of the iteration loop, to print the actual data
into the intermediate window.
Option Explicit
’ function of newton
Private Function f(x As Double) As Double
f = x ˆ 2 - 1
End Function
’ calculation of slope
Dim h As Double
h = 0.00001 * x
End Function
’ newton sceem
’ iteration loop
Do
fx = f(x0)
fsx = fs(x0)
18.4.2011
Page 22 CAD in Civil Engineering / 2011
newton = x0
flag = 1
Exit Function
newton = x0
flag = 2
Exit Function
End If
Debug.Print ” i=” & iter & ”, x0=” & x0 & ”, f(x)=” & fx & ”, f’(x)=” & fsx
Loop
End Function
E. Baeck
2.8. DATA STRUCTURES Page 23
The goal of the following example is to describe a set of mass points given by their coordinates
and mass value using data structures4 , that means user defined data types as a compound of
basic data types and user defined data types. The mass data should be stored in arrays. The
center of mass as well as the total mass should be calculated.
Outside the main program the new data type Mass is declared as user defined data type for
the mass points. Within the main program an array is declared, to store the data of all mass
points. the array is first allocated as an dynamical array without an given index range. Later
after setting the count of the mass points the length of the array is set dynamical by the use
of the Redim statement. After having committed the input data the routine to calculate the
total mass as well as the center of mass vector is called. After the calculation a list is presented
in a message box.
Please note that the option explicit is set, which means, that all variables have to be declared
explicitly. If there is an error in a variable name, the compiler often is able to find the error
checking the declarations.
’ Masspoints version 1
Sub masspoints1()
’ data input
nMass = 4
4
Data structures can be interpreted as objects without methods and only public attributes. In VBA objects
can be accessed as class modules only using pointers, but structures are accessed by value, that means like simple
variables of basic types.
18.4.2011
Page 24 CAD in Civil Engineering / 2011
’ setup masspoint 1
M(1).c = 1
M(1).M = 20#
M(1).x(1) = 0 ’ x value of mass 1
M(1).x(2) = 0 ’ y value of mass 1
M(1).x(3) = 0 ’ z value of mass 1
’ - setup masspoint 3
M(3).x(1) = 10 ’ x value of mass 3
M(3).x(2) = 10 ’ y value of mass 3
’ - setup masspoint 4
M(4).x(2) = 10 ’ y value of mass 4
End Sub
After the assignment of the input data the subprogram GetCenterOfMass is called to perform
the desired calculation of the total mass and the vector of the center of mass. As parameters the
array of the masses and the array of the center of mass vector is passed as well as the total mass.
The array ranges need not to be passed because we have the VBA functions LBound and
UBound, which are able to determine the lower and the upper bound of an array. Therefore
this functions are used to perform the loop ranges in the following example.
Dim i As Integer
E. Baeck
2.8. DATA STRUCTURES Page 25
Dim j As Integer
Next
End Sub
After having calculated the result data the result will be printed into a message box. Doing this
we have to think about line breaks. A line break is performed in VBA bei appending the control
codes carrage return and line feed. In VBA the respective constants vbCr and vbLf an be
used. After closing the messagebox the result string is also printed into the AutoCAD command
window using the method prompt of the AutoCAD object ThisDrawing.Utility (see section
4.1.1).
’ title: masses
s = ”Masses:” & vbCr & vbLf
18.4.2011
Page 26 CAD in Civil Engineering / 2011
’ title: coordinates
s = s + ”Coordinates:” & vbCr & vbLf
’ title: coordinates
s = s + ”Results:” & vbCr & vbLf
’ total Mass
s = s + ” total mass: ” & Mt & vbCr & vbLf
’ center of Mass
s = s + ” Center of mass: ” & xc(1) & ”; ”
& xc(2) & ”; ”
& xc(3) & ”; ” & vbCr & vbLf
End Sub
E. Baeck
2.9. TEXT FILES Page 27
If we want to work with files we have to talk about four basic file functions. A little example
which implements logging is given below, see also section 4.2.2.
• Open a File
A file is opened using the statement Open. The open statement has three parameters. The
first is the filename, a string. The second is the file access mode and the third parameter
sets the access channel number.5
– We can open a file for reading data, it’s called For Input.
– We can open a file for writing data, it’s called For Output. If a file is opened for
output, an old file with the same name is first deleted.
– We can open a file for appending data, it’s called For Append. If a file is opened
for append, an old file with the same name is not deleted. Data to write are written
to the end of an existing file. If no file exists with the same name, open for append
has the same effect as open for output.
• Close a File
An opened file should be closed after the work is done because the file handles of the
operating system (windows, linux, etc.) are limited. The close method has only one
parameter which is the access channel.
5
This file access mode is like in FORTRAN.
18.4.2011
Page 28 CAD in Civil Engineering / 2011
Class Modules are inserted into the vb-project tree. Each class module has it’s own node in
the tree. Within the class module all attribute and methods of an vb-object are declared. The
class modules attributes are like global variables, which are declared in the header of the class
module6
The fundamental difference between a variable of a standard type (integer, double, etc.) and
an instance7 of a class is, that Visual Basic offers an address pointer only for class instances
and not for standard data types. Therefore only instances of class modules can be handled with
so-called buildin container classes like the collection class and only instances of class modules
can be part of so-called type libraries (like the EXCEL or AutoCAD type library).
Instance addresses can only be assigned using the set operator (The use of the set operator is
described in the following examples). An instance of a class module is created by the use of
the new operator. An instance of a class module is deleted explicitly by the assignment of the
nothing address if the instance is only referenced once, i.e. by this address pointer.
Attributes and methods of a class module can be set to private and public. A private member
of a class module is only visible within its own class module. A public member however is visible
form outside of the class module and can be accessed using the general dot notation like members
of a type structure (see section 2.8 and the following examples).
The class module MassObj - this is the name of the class modules node in the vb project tree
- has three attributes:
6
I.e. in front of the first method outside of all methods.
7
This is the implementation of a class module in memory.
8
In the AutoCAD type library arrays generally starts with the lower bound index zero and therefore this array
will be declared only by specifying the upper bound index
E. Baeck
2.10. CLASS MODULES Page 29
The attribute section is followed by the section of the classes methods. If an instance is created
by an new operator call, the so-called constructor Class Initialize is called. This method
is usually used for initializations. In our example we set the density of the mass point to the
density of steel. The method Class Terminate, the so-called destructor, is called if an instance
of the class module is deleted. The content of a desctrutor method can be used for clearing. An
instance of a class module can be deleted by the assignment of the nothing address.
End Sub
End Sub
In our little class module example we use a double array to store the mass points coordinates.
Unfortunately an array attribute of a class module can not be set public. So we have to
implement access functions to pass data into the instance (set9 method) and pass data out of
the instance (get methode). To access to an array we use the index range. Each array knows its
index range and its index range can be red form the array using the LBound and UBound vb
function. The LBound provides the lower bound of the index range and the UBound provides
the upper bound of the index range.
The advantage of an access method comparing it to direct accesses is the possible error checking.
Therefore index errors can be handled by the class module itself (see the following example code).
9
We cannot use the set name because the set is used as a key word for the set operator.
18.4.2011
Page 30 CAD in Civil Engineering / 2011
setX = False
End Function
Within the following example the creation and the clearing of an instance of the MassObj
instances are discussed. We use the class module within a procedure of a standard module. The
procedure is executed with the following steps.
• The address variable m1 and m2 are declared to get the address pointers of the desired
MassObj instances.
• The first mass m1 is created using the new operator. The address of the instance is
assigned to m1 using the address assign operator set. A mass value of 3 is assigned to the
public attribute m using the dot access.
• An instance of a collection container is created and its address is assigned to the address
variable list.
E. Baeck
2.10. CLASS MODULES Page 31
• The addresses of the two masses are stored in the container using the keys10 M1 and
M2. Before we have stored the addresses in the container class the MassObj instances are
referenced only once. After having stored the addresses in the collection the addresses are
referenced twice. Addresses can be stored in a collection using the Add function. The
item parameter passes the instance address, the optional parameter key passes the key of
the instance, which is used for reading.
• Within the next step the address of mass 1 is assigned to the address pointer of mass 2.
Now mass 1 is referenced three times and mass 2 is referenced only once. If an address
looses all its references, the memory of this address is freed and the destructor of this
instance is called and executed. The memory cleaning is performed by the so-called garbage
controller11 .
Sub CreateAndDeleteAMass()
18.4.2011
Page 32 CAD in Civil Engineering / 2011
’ make changes on m1
m1.m = 5
End Sub
E. Baeck
3
One of the greatest advantages of VBA is the easy mechanism which is available to combine
different applications using their type libraries.
In our case it’s often very useful to have a common AutoCAD user-interface which offers a
wide range comfort for the user as well as for the software developer. If we try to implement
an EXCEL user-interface, we fulfil both boundary conditions. We can implement an EXCEL
user-interface first by simply using an EXCEL file as AutoCAD input file. As a second step we
implement an import method, to read the desired input data from the EXCEL input sheet.
To do this, we have to link the EXCEL type library to our AutoCAD project.
To use the COM-objects of EXCEL which are available in the EXCEL type library, we have
to set the link to the type library in our AutoCAD IDE.
33
Page 34 CAD in Civil Engineering / 2011
• Specify the import files name with the common open file dialogue, which is available as
method of the EXCEL application object. Calling the method GetOpenFileName. We
can set-up a filtering by passing a filter string, in this example the filter mask *.xls.
• Check the return of the common open file dialogue. If the dialogue is cancelled the return
will be False as string.1
• Get the input sheets pointer by calling it from the Worksheets container. The container
Worksheets is simular to the build-in Collection. We get the desired sheet by calling it
with it’s name.
• Access to the worksheets data by using the methods Cells or Range. If we want to access
to the sheets data by the use of an absolute row and column index, we can use the Cells
method.2 . On the other hand if we want to access to the sheet by the use of a name, we
should use the Range method. The Range method has in it’s simple version only one
parameter, which is the range’s name. We can also extend the Range call by relativ row
and column index values.3
• Quit the EXCEL application. You should not forget to quit the EXCEL application,
because otherwise the object, i.e. the EXCEL application, will be still active hidden in
the background and can only be closed with a taskmanager’s kill method.
Sub ExcelImportTest()
’ start EXCEL
Set e = New Excel.Application
1
In a german version the return is Falsch as a string.
2
The first argument is like the row label, the secound argument is the column label which starts also with 1.
3
In the following example we access to the content of the second row and the third column of the range
MyRange: Range(”MyRange”)(2,3)
E. Baeck
3.2. IMPORT OF AN EXCEL FILE Page 35
End Sub
18.4.2011
Part II
AutoCAD-Objects
36
4
Everything on AutoCAD has changed since AutoCAD version 13, working with the command
window remained nearly unchanged. In the context of the next sections some functions of
the AutoCAD’s Drawing Utility object are explained which can be used to communicate with
AutoCAD.
To read data from the input window AutoCAD offers a helper function, which lives in the
Utility item of the ThisDrawing object. The object ThisDrawing is the basic VBA object
which contains all the AutoCAD type library objects.
4.1.1 Prompting
To write a string to the command window the subobject Utility of the AutoCAD object This-
Drawing can be used. The method Prompt of Utility passes a specified string to the command
window.
The following example passes the string Hello AutoCAD world to the command window. The
constants vbCr and vbLf add a carriage return and a line feed character to the end of the string.
In the following example an integer value is red form the input screen. The method GetInteger
gets an optional parameter which is used as prompt in the input window. The GetInteger has
a built in error handler, which accepts only integer values as input data. But there is one
problem with the usual ESC break of the function. If GetInteger and other input functions
are canceled by ESC, the VBA kernel throws an exception1 To catch the exception in VBA in
a first step we have to hide local errors by On Local Error Resume Next If an error ocurre
an error object is created, the error is ignored and the next line is executed. So the calling
1
An exception is a controled break of a code. An exception can be caught and therefor handled by the calling
program.
37
Page 38 CAD in Civil Engineering / 2011
program is able to check the error number of the object. After the call of GetInteger the
error number has to be checked. If the error number is equal zero, no error has ocurred. If the
error number is not equal zero, the ESC has be used and the input routine was canceled. Even
though the GetInteger uses an integer as a return value, the return should be assigned to a
variant variable. A canceled call to GetInteger doesn’t return an integer and would produce
an error in an double assignment.
’ Test of GetInteger
Sub GetIntegerTest()
End Sub
In the following example a real value is red form the input screen. The method GetReal gets
an optional parameter which is used as prompt in the input window. The GetReal has a built
in error handler, which accepts only real values as input data. But there is one problem with
the usual ESC break of the function. If GetReal and other input functions are canceled by
ESC, the VBA kernel throws an exception2 To catch the exception in VBA in a first step we
have to hide local errors by On Local Error Resume Next If an error ocurre an error object
is created, the error is ignored and the next line is executed. So the calling program is able to
check the error number of the object. After the call of GetReal the error number has to be
checked. If the error number is equal zero, no error has ocurred. If the error number is not equal
zero, the ESC has be used and the input routine was canceled. Even though the GetReal uses
a double as a return value, the return should be assigned to a variant variable. A canceled call
to GetReal doesn’t return a double and would produce an error in an double assignment.
2
An exception is a controled break of a code. An exception can be caught and therefor handled by the calling
program.
E. Baeck
4.1. COMMAND WINDOW INTERACTION Page 39
’ Test of GetReal
Sub GetRealTest()
End Sub
In the following example a point data set is red form the input screen. The method GetPoint
gets two parameters, the first is the starting point to draw a connecting line to the cursor
position, the second parameter passes the prompt for the command line. The second parameter
is like in other Get-functions optional. After selection is done the method returns an array of
the dimension (0 to 2) with the three coordinate values.
The GetPoint has a built in error handler, which accepts only point data values as input data.
The general input procedure of AutoCad is called and offers the whole palett of interactive
functions to select a points data. If GetPoint and other input functions are canceled by ESC,
the VBA kernel throws an exception3 To catch the exception in VBA in a first step we have
to hide local errors by On Local Error Resume Next If an error ocurre an error object is
created, the error is ignored and the next line is executed. So the calling program is able to
check the error number of the object. After the call of GetPoint the error number has to be
checked. If the error number is equal zero, no error has ocurred. If the error number is not equal
zero, the ESC has be used and the input routine was canceled. Even though the GetPoint uses
an double array as a return, the return should be assigned to a variant variable. A canceled
call to GetPoint doesn’t return an double array and would produce an error in an assignment.
3
An exception is a controled break of a code. An exception can be caught and therefor handled by the calling
program.
18.4.2011
Page 40 CAD in Civil Engineering / 2011
’ Test of GetPoint
Sub GetPointTest()
End Sub
The AutoCAD Get-functions can be used to build up AutoCAD like line dialogs.
The following example shows a user input driven creation of some instances of the MassObj
class module (see section 2.10.1).
4. If the number of mass points to create is not reached jump to the second step and read
the next mass points data.
E. Baeck
4.2. EXAMPLES FOR GET-FUNCTIONS Page 41
• m stores the address of a mass object instance. This instances are created step by step
during the input line dialog.
• list It’s possible to create more than one mass object instance. Therefore we have to store
the instance addresses in a container object. This container object instance is created from
the build-in vb collection class module. After the creation of the mass object instances a
for loop is performed over all stored object instances. The data of each instance are listed
using the object’s method list. Then the object’s are removed form the collection using
subsequent calls of it’s method remove removing the first object pointer in the list.
To check the behavior of the programs execution we implement two helper procedures to write
subsequent messages into a log file. This two procedures live in a module4 which is called Lib.
Lib means library and is a box for non specific helper code.
• The log files name is stored in the public global variable tracefile. The initialization is
done within the procedure InitLog assigning the value of the constant string tracedefault
to the variable tracefile.
’ default filename for logging
Public Const tracedefault = ”c:“vbalog.txt”
’ logfilename
Public tracefile As String
• InitLog initializes the log file. That means an old one is deleted and a time stamp is
written into the new one. tracedefault is a constant string which contents the default
name of the log file. The log file is opened with the flag Output. The time stamp is
created with the vb build-in function now. We should not forget to close the file after we
have done our work with the statement close.
18.4.2011
Page 42 CAD in Civil Engineering / 2011
Close #1
End Sub
• AppendLog prints the next message into the log file. To hold the old information of the
log file, the log file has to be opened using the flag Append. Printing the message into
the file we also use a time stamp calling the function now. We should not forget to close
the file after we have done our work with the statement close.
End Sub
’ Initialize logging
Call InitLog
E. Baeck
4.2. EXAMPLES FOR GET-FUNCTIONS Page 43
Next
Next
18.4.2011
Page 44 CAD in Civil Engineering / 2011
Next
Exit Sub
cancellabel:
End Sub
E. Baeck
5
Primitives in Modelspace
All two or three dimensional model objects like lines, arcs, spheres etc. live in the ModelSpace
object of the AutoCAD type library. The ModelSpace object is part of the fundamental
AutoCAD object ThisDrawing which can be seen as a container for all visual basic objects.
The AcadLine object is part of the ModelSpace object and can be created by calling the
specific add function AddLine. The AddLine function is a method of the ModelSpace object
and needs two Double arrays containing the 3d-coordinates for the starting and the endpoint.
A little example is given below. First we allocate two double arrays for the data of the start and
endpoint of a line. Then in three code blocks three lines are created changing the coordinates of
the endpoint before creating them. The address of the created line instance is assigned to the
object variable lineobj. To change the line’s color, the color index value should be assigned to
the color attribute of the line object. To show the assigned color the lines visualization should
be updated using the method Update.
’ set up point 2
x2(0) = 100
’ create a line
Set lineObj = ThisDrawing.ModelSpace.AddLine(x1, x2)
lineObj.color = 1
lineObj.Update
45
Page 46 CAD in Civil Engineering / 2011
x2(0) = 100
x2(1) = 100
Set lineObj = ThisDrawing.ModelSpace.AddLine(x1, x2)
lineObj.color = 2
lineObj.Update
x2(0) = 0
Set lineObj = ThisDrawing.ModelSpace.AddLine(x1, x2)
lineObj.color = 3
lineObj.Update
End Sub
To delete lines from the drawing we can filter all objects with the type IAcadLine1 using an For
Each ... next iterator on the basis ThisDrawing.ModelSpace. An object can be deleted
calling the Delete method of the object. This is shown in the following example.
Sub DeleteLinesFromDrawing()
For Each obj In ThisDrawing.ModelSpace
If TypeName(obj) = ”IAcadLine” Then
obj.Delete
ThisDrawing.Utility.Prompt vbCr + vbLf + ”Line deleted.”
End If
Next
End Sub
1
If we don’t know the TypeName of an object, we can create this object. After the object is created, we will
see it’s type name in the so-called intermediate window of the vbaide.
E. Baeck
5.2. DELETE OBJECTS FROM MODELSPACE Page 47
Like we have seen in section 5.1 we can delete objects from the model space by iterating the
object space object by object. Within this section a library function is presented, which deletes
all objects from the ThisDrawing.ModelSpace container, the model space.
The following procedure ResetModelSpace deletes all objects from the model space and can
be applied as an initialization routine.
End Sub
The AcadSphere object is a special Acad3DSolid object and is part of the ModelSpace
object and can be created by calling the specific add function AddSphere. The AddSphere
function is a method of the ModelSpace object and needs one Double arrays containing the
3d-coordinates for the center point and one Double which specifies the radius of the sphere.
In the following example lines and spheres are created in model space in a plan circular and
star-like distribution. There result is given in figure 5.2.
• In the header section some declaration are made. We need two Double arrays for the start-
and endpoint coordinates of a line. Then we need a variable to hold the radius and the π
value.
π = 4 · arctan(1.) (5.1)
• After having created AutoCAD’s true color object AcadAcCmColor the model
space is reseted, to start with a new drawing calling our library helper procedure
ResetModelSpace.
2 22
You should avoid to setup π with only some digits or use the crude approximation 7
, because if you do this,
you will introduce a methodical relative error of in the last case 10−3 .
18.4.2011
Page 48 CAD in Civil Engineering / 2011
• Then we set up the drawing’s parameter which are the radius of the lines endpoints with
respect to the starting point, which is the center of the system as well as the radius of the
spheres and the angle increment.
• Within a loop over all angle increments we create for every increment a line and a sphere
at the endpoint of the line. So we have to calculate the polar coordinates of the lines’s
endpoints, which describes a circle around the center with the given radius r .
A line is created and the color of the line is established by the given red, green, blue values.
Because we want to draw only red lines the blue and green part of the color are set to
zero. We only have a red part and the red part is starting from 50 and increases up to it’s
maximum with 255.3
After having calculated the color’s intensity we call the SetRGB-Methode of the color
object and assign it to the line’s TrueColor attribute.
In the last step we create a sphere using the AddSphere methode of the ThisDraw-
ing.ModelSpace object. The calculated color value of the increment now is used to
create green spheres. Therefore we assign a zero value to the red und the blue part of the
RGB value and use the calculated color only for the green part for the AcadAcCmColor
object.
Dim i As Integer
Dim r As Double
Dim phi As Double
Dim pi As Double ’ pi constant
E. Baeck
5.3. ACADSPHERE OBJECT Page 49
’ initialisation
r = 100 ’ Radius
rs = 10 ’ Radius of the spheres
del = 30 ’ step angle
Next
End Sub
18.4.2011
Page 50 CAD in Civil Engineering / 2011
Figure 5.2 shows a line and a sphere with dark colors at the position 0◦ . At the end position we
see a line and a sphere with the maximum color value of it’s used RGB color.
E. Baeck
Part III
Sample Projects
51
6
Random Masspoints
Within this chapter a program is developed for the creation of a random distribution of mass
points. The mass value of a point as well as the position of the mass point is calculated as
random. Several distribution spaces are implemented. At the end an effective mass point is
calculated with a mean mass value and a mean position, the so-called centre of mass.
The data of a mass point is handled within a class module. To handle all the created mass
points a container class module is introduced basing on the vba build-in class module collection.
The class module for our mass point object will be an extension of the class module of section
2.10.1.
6.1.1 Attributes
The Double array for the mass points position as well as the value for the mass value adopted.
The color index value is substituted by AutoCAD’s true color class module AcadAcCmColor.
Because we will have sqheres as mass point’s volumns, we specify the density of the mass point,
which is stored in a Double value. The address pointer of the class module’s instance is stored
in a variable of Acad3DSolid.
52
6.1. CLASS MODUL MASS Page 53
The following methods are adopted form the class module of section 2.10.1.
6.1.2 Methods
End Sub
If we want to clear up created instances we can do that within the destructor. Because vba uses
a garbage controller which deletes objects which are no longer referenced. Therefore the explicit
clearing of unused instances is not really needed.
End Sub
To be able to visualize the mass point’s volume, we have to calculate the radius from the given
density. This can be done with the following formula.1
1
3·m 3
r= (6.1)
4·π·ρ
1
Note that π is calculated with the arctan function.
18.4.2011
Page 54 CAD in Civil Engineering / 2011
pi = Atn(1) * 4#
rs = ((3# * m) / (4# * pi * rho)) ˆ (1# / 3#)
End Sub
The following method create creates the sphere of a mass point. As input parameter the red,
green, blue parts of the true color are passed. The error checker of the function checks the mass
value and the density value. The function returns False if the error checking of the function
detects an error. If no error is found the function returns True.
After the error checking the true color object is prepared with SetRGB. Then the radius of
the sphere is calculated and a sphere object is created at the position of the mass point. After
assigning the true color to the sphere object the function returns the True return code.
’ error checking
’ mass value ok?
If m < 0.0000000001 Then
Create = False
Exit Function
End If
’ density ok
If rho < 1E-20 Then
Create = False
Exit Function
End If
’ every ok!
Create = True
E. Baeck
6.2. CLASS MODUL MASSES Page 55
End Function
The instances of the MassObj are stored in the container class module Masses. Masses will
handle the creation of random mass point objects. Information of the stored data should be
printed into a log file.
6.2.1 Attributes
6.2.2 Methodes
The constructor is used to create the centre of mass object CoM and the collection object List.
The destructor is not used for clearing.
’ initializations
Private Sub Class Initialize()
End Sub
18.4.2011
Page 56 CAD in Civil Engineering / 2011
The method initializes first the random number generator calling the build-in routine
Randomize. The random numbers are calculated by a call of the function Rnd. The range
of the random numbers is given by the interval 0 to 1. Therefore the random mass values are
given by
Next
E. Baeck
6.2. CLASS MODUL MASSES Page 57
MObj.M = M
Call MObj.setX(x)
Call MObj.SetRadius
Next
End Sub
The mass points spheres can be created using the method CreateSpheres. The method iterates
all available mass point instances stored in the container List and call their method Create. As
parameters we pass the RGB color values to the Create method. The coding of CreateSpheres
is given below.
’ R G B
If MObj.Create(255, 0, 0) Then
s = ”Mass sphere ” & i & ” is created.”
Else
s = ”Mass sphere ” & i & ” is not created.”
End If
Next
End Sub
18.4.2011
Page 58 CAD in Civil Engineering / 2011
To test the class modules of this chapter, we write a little frame subroutine for testing. The
subroutine should read the input data from an excel file and should perform the creation of the
mass objects as well as it’s creation as AutoCad sphere objects.
To create our random mass point distribution we need the following input parameters.
To check the creation of the random mass distribution we need some output data, which are
written into the EXCEL-sheet’s protocol section. The following data for every mass point are
printed.
E. Baeck
6.3. FRAME APPLICATION Page 59
The sample application performs the steps we have discussed in section 3.2. First we start
an EXCEL application object.. Then we call it’s GetOpenFileName method to specify the
EXCEL file with the input data. After that we select the EXCEL sheet with the input data
from the Worksheets container. The next step will give us the desired input data by the use
of the sheets Range object. Here we have to be very carefully with the usage of the range’s
name. If a unknown name is used the code is crashing and the EXCEL application object will
hang.2
The next statement resets the modelspace. The container for the mass points is created. The
method CreateRndMasses of the container creates a random mass point distribution within
a cube range. After that the AutoCAD sphere objects are created. The last step closes the
EXCEL input file and quites the EXCEL task.
Sub CreateSomeRandomMassPoints()
’ linking to EXCEL
Set e = New Excel.Application
2
Such problems can be solved by applying an errorhandler, which catches the problem and avoid the crashing
of the program.
18.4.2011
Page 60 CAD in Civil Engineering / 2011
’ get EXCEL-Sheet
Set s = e.Worksheets(”Masses”)
’ create spheres
Call MList.CreateSpheres
End Sub
E. Baeck
6.3. FRAME APPLICATION Page 61
Figure 6.4 shows two random distributions with 200 mass points in a cube with edge length
2000. The left figure shows a mass range from 2 to 100, the right figure a range from 10 to 200.
In the 2nd step of the implementation of sample 1, we don’t want to close the excel-sheet,
because we want to check the control-values of the output section immediately. Therefore we
set the closing section of the excel application on comment.
’ create spheres
Call MList.CreateSpheres(s)
Set e = Nothing
18.4.2011
Page 62 CAD in Civil Engineering / 2011
After that we want to create and visualize the sphere of the effective mass at the centre of mass’s
position. This we will implement in the method CreateSpheres. This methode also will get a
new parameter, which contents the pointer to the excel-sheet. The excel-sheet pointer is used
for the printing of the output data discussed above. After the excel output is done, the sphere
for the effective mass is created. The code of the extended version of CreateSpheres is given
below.
’ ... sums
Dim xs(2) As Double
Dim ms As Double
’ R G B
If MObj.Create(255, 0, 0) Then
s.Range(”output”)(nRow, 1) = ”S-” & i
s.Range(”output”)(nRow, 2) = MObj.M
For j = 0 To 2
s.Range(”output”)(nRow, 3 + j) = MObj.x(j)
Next
Else
s.Range(”output”)(nRow, 1) = ”Mass sphere ” & i & ” is not created.”
End If
E. Baeck
6.3. FRAME APPLICATION Page 63
’ extrem values
’ - initialisation
If i = 1 Then
For j = 0 To 2
xmin(j) = MObj.x(j)
xmax(j) = MObj.x(j)
Next
mmax = MObj.M
mmin = MObj.M
End If
’ next line
nRow = nRow + 1
Next
’ next line
nRow = nRow + 2
18.4.2011
Page 64 CAD in Civil Engineering / 2011
For j = 0 To 2
s.Range(”output”)(nRow, 3 + j) = xmax(j)
Next
End Sub
E. Baeck
6.3. FRAME APPLICATION Page 65
Figure 6.5 shows the result, calling the new version of CreateSpheres.
18.4.2011
Part IV
Exercises
66
7
If you submit a exam project, the following components are unconditional needed.
• Description how to handle the developed software from the view of a general user.
• Description how to use the software from the view of a software developer. That means
we need a description of all interfaces and a short outline for each software component
(function, subroutine, module or class module).
• If the software uses input data, the format of the input data should be declared (for
example the format of an input file).
• if the software creates some output data, the format of the output data should be declared.
67
Page 68 CAD in Civil Engineering / 2011
The colored hedgehog is a sphere with radius rH consisting of lines and little spheres. The lines
of the hedgehog start from the centre point of the sphere and they end up at the surface of the
sphere. At the end of each line there is a little sphere with radius rE . The surface of a sphere
can be specified easyly by spherical coordinates, that is an inclination respectively an elevation
angle θ and an azimuth angle ϕ.
Besides the values for the radius of hedgehog and little spheres we have to specify the angle steps
for the azimuth angle ∆ϕ as well as the inclination/elevation angle ∆θ.
Figure 7.1 shows the usage of spherical coordinates. In the left picture a spherical coordinate
system with origin O, zenith direction Z and azimuth axis A is given. The point has radius
r = 4, inclination θ = 70◦ , and azimuth ϕ = 130◦ . An alternate spherical coordinate system is
given in the right picture, using elevation from the reference plane instead of inclination from
the zenith. The point has radius r = 4, elevation θ = 50◦ , and azimuth ϕ = 130◦ .
The colour interpolation of the directions should be superposed if the spheres position is in
between the axis.
1
rgb(255,0,0) is light red.
2
rgb(0,255,0) is light green.
3
rgb(0,0,255) is light blue.
E. Baeck
Index
line, 45 Range, 32
sphere, 47 Worksheets, 32, 59
EXCEL-Sheet, 16
Acad3DSolid, 47, 53 Exception, 37–39
AcadAcCmColor, 47, 53
SetRGB, 48, 55 Faculty and Overflow, 9
AcadLine, 45 False, 55
color, 45 File, 24
TrueColor, 48 Close, 24, 41, 42
Update, 45 Line Input, 24
AcadSphere, 47 Open, 24
AddLine, 45 Append, 24, 42
AddSphere, 47 Input, 24
Assigning, 7 Output, 24, 41
azimuth angle, 64 Print, 24
For Each ... next, 46
Class Module, 25 For...Next, 8
Class Initialize, 26 Function, 13
Collection, 27, 32, 41, 53
garbage controller, 28
Add, 28, 57
Get Functions, 40
Remove, 41
GetInteger, 37, 40
Colored Hedgehog, 64
GetPoint, 39, 40
Command Button, 16
GetReal, 38, 40
Const, 41
global variable, 41
constant, 41
Constructor, 54 IACadLine, 46
inclination angle, 64
Debug object, 7
InputBox function, 10
Delete, 46
Destructor, 54 LBound, 26
Do...Loop, 10, 13 line dialog, 40
Double, 8 Byte float, 11
memory leaks, 28
End Function, 13 module, 41
Error handler, 37–39 MsgBox function, 10
EXCEL, 31
New Operator, 25, 27
Application, 32, 59
Newton Algorithm, 13, 16
Cells, 32
Nothing, 25
GetOpenFileName, 32, 59
Quit, 32 polar coordinates, 48
69
Page 70 CAD in Civil Engineering / 2011
Private, 25
Prompt, 37
Public, 25, 26
Randomize, 57
Relative Precision, 10
RGB, 48
Rnd, 57
Taskmanager, 32
ThisDrawing, 37, 45
ThisDrawing.ModelSpace, 45–47
timestamp, 41
now, 41
True, 55
TypeName, 46
UBound, 26
Utility object, 37
E. Baeck