You are on page 1of 74

CAD in Civil Engineering

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

3 Using EXCEL as GUI 33


3.1 EXCEL Type Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2 Import of an EXCEL File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

II AutoCAD-Objects 36

4 Concepts of a User Command Dialog 37

iii
Page iv CAD in Civil Engineering / 2011

4.1 Command Window Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37


4.1.1 Prompting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.1.2 Get Integer Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.1.3 Get Real Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.1.4 Get Point Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 Examples for Get-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.2.1 Creating some MassObj-Instances . . . . . . . . . . . . . . . . . . . . . . 40
4.2.1.1 The Line Dialogs Layout . . . . . . . . . . . . . . . . . . . . . . 40
4.2.2 Used Object Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2.3 Helper Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2.4 Visual Basic Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5 Primitives in Modelspace 45
5.1 AcadLine Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.2 Delete Objects from ModelSpace . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3 AcadSphere Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

III Sample Projects 51

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

7 Exam Projects SS10 67


7.1 General Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.2 Colored Hedgehog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

E. Baeck
Part I

Introduction to VBA

1
1

General Statements

1.1 AutoCad - Versions and VBA

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.

Figure 1.1: VBA Download Page

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

The VBA-IDE2 can be started with the command vbaide.


1
The VBA development package can be downloaded from the following link.
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=12715668&linkID=9240618
2
IDE: Integrated Development Environment

2
1.3. MACRO MANAGER Page 3

1.3 Macro Manager

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).

Figure 1.2: Macro Manager

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

Figure 1.3: VBA Manager

E. Baeck
2

Basics in VBA

2.1 Data Types, Variables and Constants

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.

2.1.1 Data Types

Table 2.1 shows the available data types of VBA.

Type Comment Range


Byte one byte integer, no negative values 0, 1, 2, · · · , 255
Integer two byte integer number −32768, · · · , +32767
Long four byte integer number −231 , · · · , 231 − 1
Single four byte float number ±1, 4 · 10−45 · · · 3, 4 · 10+38
Double eight byte float number ±4, 9 · 10−324 · · · 1, 8 · 10+308
Boolean two byte flag only True and False
String text stream up to 2GBytes "This is an Example"
Object 4 byte address of an object instance set s = new Line
Variant a container for all data types

Table 2.1: VBA Data Types

5
Page 6 CAD in Civil Engineering / 2011

2.1.2 Declaration of Variables and Constants in VBA

2.1.2.1 Explicit Declarations

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.

2.1.2.2 Implicit Declarations

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).

Type Character Example


Byte not available
Integer % a% = 1
Long & b& = 2
Single ! c! = 3.1
Double # d# = 4.1
String $ s$ = "So What"’

Table 2.2: VBA Implicit Declaration

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.

2.2.1 Unary Operators

Unary operators are working only on one value, therefor unary. In VBA there are the following
unary operators available.

Operator Comment Example


+ plus operator a = 2 >>> x = +a >>> +2
- minus operator a = 2 >>> x = -a >>> -2
not logical inverse a = False >>> x = not a >>> True

2.2.2 Arithmetic Operators

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.

Operator Comment Example


+ sum operator x = 2+3 >>> 5
- substraction operator x = 4-2 >>> 2
* product operator x = 2*4 >>> 8
/ division operator x = 9/2 >>> 4
x = 9./2. >>> 4.5
^ power operator x = a^2
& concatenate of strings with values s = "a = " & a

2.2.3 Comparison Operators

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

Operator Comment Example


< less than x = 23 < 13 >>> False
<= less equal x = 23 <= 23 >>> True
> greater x = 23 > 13 >>> True
>= left shift of bits x = 23 >= 23 >>> True
= equal x = 23 = 23 >>> True
<> non equal x = 23 <> 23 >>> False

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

Operator Comment Example


and logical and x = 1 < 2 and 2 < 3 >>> True
or logical or x = 1 < 2 or 2 > 3 >>> True
xor logical or x = True >>> y = False >>> x xor y >>> True
not logical not x = not (1 < 2) >>> False

The truth table for the and operator ∧ is given as follows.

True ∧ True = True (2.1)


True ∧ False = False
False ∧ True = False
False ∧ False = False

The truth table for the or operator ∨ is given as follows.

True ∨ True = True (2.2)


True ∨ False = True
False ∨ True = True
False ∨ False = False

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

2.3 Assigning Values

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.

How to assign values to variables

’ Example of the session on 09-04-28

’ Example 1
’ Summing up 2 values and writing a log to the output window

’ >> Theme: Assigning a value

Sub Example 1()

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.

Simple loop to add up some numbers

’ Example 2
’ Summing up all odd integers from 1 to 10
’ Writing the log for i-Values graeter 5

’ >> Theme: For-loop with conditional logging

Sub Example 2()

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

2.5 Data Types

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.

Checking data types applying the factorial

’ Example 3
’ Calculating the faculty for several data types

’ >> Theme: For-loop and overflow

Sub Example 3()

’ Dim f As integer
’ Dim f As long
’ Dim f as single
Dim f As Double
Dim i As Integer
Dim n As Integer

’ n! is calculated with the following value


n = 170

’ be carefull with the initialization


f = 1
For i = 1 To n

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

2.6 Calculation of Precision

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 .

The relative precision is returned by the function as return value.

Main program to calculate a data types precision

’ main-program of precision

Sub prec main()

Dim key As String ’ "text"-variable < 2 * 10^9 characters


Dim pre As Double ’ (largest number in long with sign)

’ input key value using an inputbox


key = "single"

’ call of the inputbox


key = InputBox("Input of data type (single/double):", "Input", key)

MsgBox "Selected key value :" + key, vbInformation, "Information"

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.

Subroutine to calculate a data types precision

’ calculation of the precision

Function precision(k As String) As Double

’ single type variables


Dim x1s As Single
Dim x2s As Single
Dim epss As Single

’ evaluate single case


If k = "single" Then

x1s = 1! ’ single constant


epss = 1!

’ impclicit loop
Do

epss = epss / 2! ’ reduce the eps


x2s = x1s + epss

Debug.Print "x1s = " & x1s & ", epss = " & epss
’ check if eps still exists
If x1s = x2s Then Exit Do

Loop

’ setup return value with one step backward


precision = epss * 2!

’ evaluate double case


ElseIf k = "double" Then

’ error case: return = -1 because -1 is not a precision value


Else
MsgBox "Key ’" + k + "’ is not supported!", vbCritical, "Error"
precision = -1

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

2.7 Newton Algorithm

The following example implements the algorithm of newton to search the roots of a given func-
tion.

A pure VBA - Version is given in the first program version

2.7.1 Pure VBA Version with Smart Slope

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.

Main routine of the implementation of Newton’s algorithm in a simple version

’ Newton algorithm
Sub example 5()

Dim nmax As Integer ’ maximum iterations


Dim iter As Integer ’ number of iterations
Dim flag As Integer ’ return flag
Dim eps As Double ’ precision
Dim x0 As Double ’ Solution value

nmax = 20
nmax = InputBox("Maximum of iterations", "Input", nmax)

eps = 0.000001
x0 = newton(iter, nmax, eps, flag)

’ case: solution found


If flag = 0 Then

MsgBox "result = " & x0 & " (Iterations: " & iter & ")"

’ case: no solution found


Else

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.

Newton function of the implementation of Newton’s algorithm in a simple version

’ user function f(x)

Function f(x As Double) As Double

f = x ^ 2 + 1

End Function

Function fs(x As Double) As Double

Dim delx As Double

delx = 0.000001

fs = (f(x + delx / 2#) - f(x - delx / 2#)) / delx

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

If Abs(fx) < eps Then


newton = x
Exit Function
End If

’ f’(x) = 0 ?
If Abs(fsx) < eps Then
newton = 0

x = x + stp

’ if max. iterations are reached, then exit


’ vanishing slope
If n >= nmax Then
flag = 1
Exit Function
End If

n = n + 1 ’ Step besides as a new try


GoTo start ’ start againt, next try

End If

’ max of iteration reached, then exit (Error 2)


If n >= nmax Then
newton = 0
flag = 2
Exit Function
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

2.7.2 EXCEL VBA Version with EXCEL-Sheet-GUI

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.

Figure 2.1: XLS-Sheet GUI

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.

Figure 2.2: Click Event Function for a Command Button

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

Eventfunction for an Run button

’ Event function to start the newton calculation


Private Sub CommandButton1 Click()

Dim x0 As Double ’ starting position


Dim eps As Double ’ Precision
Dim iterX As Integer ’ max. number of iterations
Dim iter As Integer ’ number of performed iterations
Dim flag As Integer ’ return code flag

’ 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)

’ output to the xls sheet


’ case: result
If flag = 0 Then
Range("Root") = x0
Range("Iterations") = iter

’ case: slope problem


ElseIf flag = 1 Then
Range("Root") = "Error: vanishing slope"
Range("Iterations") = iter

’ case: no result found


ElseIf flag = 2 Then
Range("Root") = "Error: No root found"
Range("Iterations") = iter

’ case: unsupported flag


Else
Range("Root") = "Error: unknown error"
Range("Iterations") = 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

Private Function fs(x As Double) As Double

Dim h As Double
h = 0.00001 * x

fs = (f(x + h / 2) - f(x - h / 2)) / h

End Function

’ newton sceem

Public Function newton(x0 As Double, iterX As Integer,


eps As Double,
flag As Integer, iter As Integer) As Double

Dim fx As Double ’ function value


Dim fsx As Double ’ functions slope

iter = 0 ’ initialization of the iteration counter


flag = 0 ’ case of success

’ iteration loop
Do

fx = f(x0)
fsx = fs(x0)

18.4.2011
Page 22 CAD in Civil Engineering / 2011

’ case: root found


If Abs(fx) <= eps Then

newton = x0 ’ set the return value


Exit Function

’ case: min/max point vanishing slope


ElseIf Abs(fsx) <= eps Then

newton = x0
flag = 1
Exit Function

’ case: root not found


ElseIf iter > iterX Then

newton = x0
flag = 2
Exit Function

End If

’ case: perform iteration


x0 = x0 - fx / fsx
iter = iter + 1

Debug.Print ” i=” & iter & ”, x0=” & x0 & ”, f(x)=” & fx & ”, f’(x)=” & fsx

Loop

End Function

E. Baeck
2.8. DATA STRUCTURES Page 23

2.8 Data Structures

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.

Option Explicit ’ every variable has to be declared explicitly

’ data type for a mass point


Type Mass
x(1 To 3) As Double ’ coordinates: x,y,z
M As Double ’ mass value
c As Integer ’ colour index (etc.)
End Type

’ Masspoints version 1

Sub masspoints1()

Dim nMass As Integer ’ number masspoints


Dim M() As Mass ’ array of masspoints
Dim i As Integer ’ for counter variable
Dim xc(1 To 3) As Double ’ vector of the center of mass
Dim Ms As Double ’ sum of the masses

’ data input
nMass = 4

’ allocate the memory for the masspoints


ReDim M(1 To nMass) ’ Mass 1,2,3,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

’ Initialization of the masspoint 2-4 using data of point 1


For i = 2 To nMass
M(i) = M(1) ’ total data of point 1 is copied
Next

’ Overwrite special data for points 2-4


’ - setup masspoint 2
M(2).x(1) = 10 ’ x value of mass 2

’ - 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

’ calculation of the center of mass


Call GetCenterOfMass(M, xc, Ms)

’ list results into a Messagebox


Call ListResults(M, xc, Ms)

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.

’ calculation of the center of mass

Sub GetCenterOfMass(M() As Mass, xc() As Double, Mt As Double)

Dim i As Integer

E. Baeck
2.8. DATA STRUCTURES Page 25

Dim j As Integer

’ calculation of the total mass


Mt = 0#
For i = LBound(M) To UBound(M)
Mt = Mt + M(i).M
Next

’ calculation of mean values for the coordinates


’ loop of the components
For i = 1 To 3

xc(i) = 0 ’ initialization of the component


’ in this case VERY important

’ loop over all masses


For j = LBound(M) To UBound(M)
xc(i) = xc(i) + M(j).M * M(j).x(i)
Next
xc(i) = xc(i) / Mt

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).

’ list results into a messagebox

Sub ListResults(M() As Mass, xc() As Double, Mt As Double)

Dim s As String ’ content of the messagebox


Dim i As Integer ’ loop counter

’ title: masses
s = ”Masses:” & vbCr & vbLf

’ output of mass values


For i = LBound(M) To UBound(M)

18.4.2011
Page 26 CAD in Civil Engineering / 2011

s = s + ” Mass ” & i &” : ” & M(i).M & vbCr & vbLf


Next

’ title: coordinates
s = s + ”Coordinates:” & vbCr & vbLf

’ output coordinates of the masses


For i = LBound(M) To UBound(M)
s = s + ” Mass ” & i & ” : ” & M(i).x(1) & ”; ”
& M(i).x(2) & ”; ”
& M(i).x(3) & ”; ” & vbCr & vbLf
Next

’ 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

’ output into the messagebox


MsgBox s, vbInformation, ”Masses”

’ printout in command window (see below)


s = vbCr & vbLf & s
ThisDrawing.Utility.Prompt s

End Sub

E. Baeck
2.9. TEXT FILES Page 27

2.9 Text Files

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.

• Writing into a File


If text data should be written into a file, the print method can be used. The print method
has two parameter. The first parameter sets the file access channel. The second parameter
passes a the output string.

• Reading from a File


If text data should be read from a file, the line input method can be used. The line
input method has two parameter. The first parameter sets the file access channel. The
second parameter passes a string variable which is used to receive the input data.

5
This file access mode is like in FORTRAN.

18.4.2011
Page 28 CAD in Civil Engineering / 2011

2.10 Class Modules

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).

2.10.1 A Mass Point Class Module

In the following example a mass point will be modelled by a class module.

The class module MassObj - this is the name of the class modules node in the vb project tree
- has three attributes:

• a double array of its coordinates,8 .

• a double mass value and

• a double value for the density of the sphere’s material

’ Attributes of the object

Dim xi(2) As Double ’ coordinates


’ arrays are PRIVATE in VBA
’ therefor we need access-functions (get/set)
Public m As Double ’ mass value
Public rho As Double ’ density of the mass

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.

’ constructor is called with the new operator

Private Sub Class Initialize()

rho = 0.00000784 ’ density of steel by default

End Sub

’ destructor is called if the object is deleted from the memory


’ by assigning ”nothing”

Private Sub Class Terminate()

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

’ pass data to the x-array

Public Function setX(x() As Double) As Boolean

setX = False

’ check the parameters


If LBound(x) < 0 Then Exit Function
If UBound(x) > 2 Then Exit Function

’ copy the values


setX = True
For i = 0 To 2
xi(i) = x(i)
Next

End Function

’ get function of the coordinates vector


’ ... = m.x(i)

Public Function x(i As Integer) As Double


x = 0#
If i < 0 Or i > 2 Then Exit Function
x = x(i)
End Function

2.10.2 Create and Delete

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.

• The second mass m2 is created like m1 and a mass value of 4 is assigned.

• 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 .

’ create and delete a MassObj

Sub CreateAndDeleteAMass()

’ only create an address variable


Dim m1 As MassObj
Dim m2 As MassObj

’ create an object in memory


Set m1 = New MassObj
m1.m = 3

’ create 2nd mass object


Set m2 = New MassObj
m2.m = 4

’ create a collection instance (object)


Dim list As New Collection

’ insert the 1st mass object into the container


list.Add Item:=m1, key:=”M1”

’ insert the 2nd mass object into the container


list.Add Item:=m2, key:=”M2”

’ assign object addresses


Set m2 = m1
10
Addresses of instances can be stored in a collection with an optional key name.
11
The garbage controller frees all memory blocks which have loosed their references and are unaccessible. This
is an advantage comparing it with the situation of C/C++. In C/C++ unaccessible memory blocks are not freed
and therefore results memory leaks.

18.4.2011
Page 32 CAD in Civil Engineering / 2011

’ make changes on m1
m1.m = 5

’ delete the mass object


Set m1 = Nothing

End Sub

E. Baeck
3

Using EXCEL as GUI

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.

3.1 EXCEL Type Library

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.

The link can be set within the link man-


ager of the project, which can be called
from the extras menu of AutoCAD. In
figure 3.1 we see the type library of
the Microsoft EXCEL 11.0. This link
should be set by checking the corre-
sponding check button. If the link is set,
the COM-objects of EXCEL are avail-
able in our program.

Figure 3.1: Set up the EXCEL Type Library Link

33
Page 34 CAD in Civil Engineering / 2011

3.2 Import of an EXCEL File

To import the data of an EXCEL-file, we should do the following steps.

• Create an EXCEL application object.

• 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.

’ How to use EXCEL as GUI-Frontend

Sub ExcelImportTest()

’ start EXCEL
Set e = New Excel.Application

’ specify XLS-input file


file = e.GetOpenFileName(fileFilter:=”Input (*.xls),*.xls”)

’ handle canceling of the dialog


If file = ”False” Then Exit Sub

’ open the specified XLS file, the Workbook


e.Workbooks.Open FileName:=file

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

’ get the address of the desired Worksheet


Set s = Excel.Worksheets(”Input”)

’ read the content of A3 (row: 1 / column 3)


t = s.Cells(1, 3)

’ quit the EXCEL application


’ !!! don’t forget it !!!
e.Application.Quit

End Sub

18.4.2011
Part II

AutoCAD-Objects

36
4

Concepts of a User Command Dialog

4.1 Command Window Interaction

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.

ThisDrawing.Utility.Prompt "Hello AutoCAD World!" & vbCr & vbLf

4.1.2 Get Integer Values

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()

Dim inp As Variant

On Local Error Resume Next


inp = ThisDrawing.Utility.GetInteger(vbCr & vbLf & ”Type an integer:”)
If Err.Number <> 0 Then
MsgBox ”Input error number: ” & Err.Number
Else
MsgBox ”Input ok: ” & inp
End If

End Sub

4.1.3 Get Real Values

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()

Dim inp As Variant

On Local Error Resume Next


inp = ThisDrawing.Utility.GetReal(vbCr & vbLf & ”Input of Real value:”)
If Err.Number <> 0 Then
’MsgBox ”Error number: ” & Err.Number
Else
MsgBox ”Real value = ” & inp
End If

End Sub

4.1.4 Get Point Values

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()

Dim inp As Variant

On Local Error Resume Next


inp = ThisDrawing.Utility.GetPoint(, ”Where is the position: ”)
If Err.Number <> 0 Then
MsgBox ”Input error number: ” & Err.Number
Else
’ inp: dim inp(2) as double >> 0,1,2
MsgBox ” Point: ” & inp(0) & ” — ” & inp(1) & ” — ” & inp(2)
End If

End Sub

4.2 Examples for Get-Functions

The AutoCAD Get-functions can be used to build up AutoCAD like line dialogs.

4.2.1 Creating some MassObj-Instances

The following example shows a user input driven creation of some instances of the MassObj
class module (see section 2.10.1).

4.2.1.1 The Line Dialogs Layout

The input dialog runs in the following steps.

1. Read the number of mass points to create with GetInteger.

2. Read the mass value of the mass point with GetReal.

3. Read the coordinates of the mass point with GetPoint.

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

4.2.2 Used Object Pointer

The following object pointers are used.

• 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.

4.2.3 Helper Procedures

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.

’ Initalization for logging


Public Sub InitLog()

’ use the default filename


tracefile = tracedefault

’ initalize the logfile


Open tracefile For Output As #1
Print #1, Now & ” Start logging...”
4
The module is inserted by a right click on the project tree. The standard name should be changed to Lib.

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.

’ Append log information


Public Sub AppendLog(s As String)

Open tracefile For Append As #1


Print #1, Now & ”: ” + s
Close #1

End Sub

4.2.4 Visual Basic Code

’ create a mass object from ACad command window

Public Sub CreateMassFromCommandWnd()

Dim m As MassObj ’ MassObj - address variable

Dim list As New Collection ’ List of mass data


Dim inp As Variant ’ Input from command window

’ Initialize logging
Call InitLog

’ Read the number of the masses


On Local Error Resume Next
inp = ThisDrawing.Utility.GetInteger(vbCr & vbLf & ”Number of Masses:”)
If Err.Number <> 0 Then GoTo cancellabel

’ log the number of masses


Call AppendLog(”Create ” & inp & ” mass objects.”)

’ loop over all masses


nmasses = inp
For i = 1 To nmasses

Set m = New MassObj ’ create the next mass

E. Baeck
4.2. EXAMPLES FOR GET-FUNCTIONS Page 43

’ read the mass value


inp = ThisDrawing.Utility.GetReal(vbCr & vbLf & ”Mass value of mass ” &
i & ”:”)
If Err.Number <> 0 Then GoTo cancellabel
m.m = inp

’ log the number of masses


Call AppendLog(”Mass ” & i & ”: ” & m.m)

’ read the mass position


inp = ThisDrawing.Utility.GetPoint(, vbCr & vbLf & ”Mass position: ”)
If Err.Number <> 0 Then GoTo cancellabel
If Not m.setXV(inp) Then
Call MsgBox(”Can not copy data to coordinate array!”, vbCriti-
cal, ”Error”)
End If

’ log the number of masses


Call AppendLog(”Mass ” & i & ”: ” & m.x(0) & ”, ” & m.x(1) & ”, ” & m.x(2))

’ store the mass object in the collection


list.Add Item:=m, key:=”Mass-” & i

Next

’ List the mass data


Call AppendLog(”List of ” & list.Count & ” mass objects:”)
For i = 1 To list.Count

’ get the mass address of item i


Set m = list(i) ’ List.Item(i)

’ log the number of masses


Call AppendLog(”Mass ” & i & ”: ” & m.m)
Call AppendLog(”Mass ” & i & ”: ” & m.x(0) & ”, ” & m.x(1) & ”, ” & m.x(2))

Next

’ Delete the collection


AppendLog (”Delete the Collection”)
For i = 1 To list.Count

’ delete the 1st item


Set m = list(1)

18.4.2011
Page 44 CAD in Civil Engineering / 2011

’ delete the content


Set m = Nothing

’ delete the address


list.Remove (1)

Next

Exit Sub

cancellabel:

Call ThisDrawing.Utility.Prompt(vbCr & vbLf & ”*** canceled by the user***”)

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.

5.1 AcadLine Object

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 line can be created interactively with the command line.

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.

’ Create a AutoCad line object


Sub CreateLineTest()

Dim x1(2) As Double ’ 1st point: 0:x / 1:y / 2:z


Dim x2(2) As Double ’ 2nd point: 0:x / 1:y / 2:z

’ 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

Figure 5.1: Result of the Examples Code

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

5.2 Delete Objects from ModelSpace

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.

’ Delete all objects in modelspace


Public Sub ResetModelspace()

’ iterate all objects in modelspace


For Each obj In ThisDrawing.ModelSpace

’ delete the found object


obj.Delete
Next

End Sub

5.3 AcadSphere Object

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.

A sphere can be created interactively with the command 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.

The procedure has the following structure.

• 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.

• Then we calculate pi as a result of an arctan call as follows.2

π = 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 .

x (ϕ) = r · cos(ϕ) (5.2)


y(ϕ) = r · sin(ϕ)

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.

The example’s code is given below.

’ Lines and Spheres


Sub LinesAndSpheres()

Dim x1(2) As Double ’ Starting point


Dim x2(2) As Double ’ End point

Dim i As Integer
Dim r As Double
Dim phi As Double
Dim pi As Double ’ pi constant

DegRad = Atn(1#) / 45#

’ create Truecolor object


Set col = New AcadAcCmColor

’ Reset the modelspace


Call ResetModelspace
3
A RGB color has a minimum value of 0 and a maximum value of 255. This is exactly the range of one byte
without considering the sign.

E. Baeck
5.3. ACADSPHERE OBJECT Page 49

’ initialisation
r = 100 ’ Radius
rs = 10 ’ Radius of the spheres
del = 30 ’ step angle

’ walk around the origin x1(2)


For i = 1 To 360 / del ’ 30◦ steps

’ calculaltion of the endpoint coordinates


phi = del * (i - 1) * DegRad
x2(0) = r * Cos(phi)
x2(1) = r * Sin(phi)

’ Create the line object


Set line = ThisDrawing.ModelSpace.AddLine(x1, x2)

’ set up the color using RGB-values


’ black : 0, 0, 0
’ white : 255,255,255
’ dark red: 128, 0, 0
rcol = 50 + (i - 1) / (360 / del) * 205 * 12 / 11
Call col.SetRGB(rcol, 0, 0)
line.TrueColor = col
line.Update

’ Create the sphere object


Set sphere = ThisDrawing.ModelSpace.AddSphere(x2, rs)
Call col.SetRGB(0, rcol, 0)
sphere.TrueColor = col
sphere.Update

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.

Figure 5.2: Lines and Spheres

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.

6.1 Class Modul Mass

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.

’ Attributes of the object

Dim xi(2) As Double ’ coordinates


’ arrays are PRIVATE in VBA
’ therefor we need access-functions (get/set)
Public m As Double ’ mass value
Public rho As Double ’ density of the mass

Public rs As Double ’ radius of the sphere


Private col As AcadAcCmColor ’ TrueColor object
Private s As Acad3DSolid ’ pointer to the sphere object

52
6.1. CLASS MODUL MASS Page 53

The following methods are adopted form the class module of section 2.10.1.

• Class Initialize to performe special initializations.

• Class Terminate to performe special clearings.

• setX and setXV, to assign the coordinates of the mass point.

• x, to get a mass point’s coordinate values.

6.1.2 Methods

Within the Constructor we create the true color object AcadAcCmColor.

’ constructor is called with the new operator

Private Sub Class Initialize()

rho = 0.00000784 ’ density of steel by default

Set col = New AcadAcCmColor ’ create the color object

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.

’ destructor is called if the object is deleted from the memory


’ by assigning ”nothing”

Private Sub Class Terminate()

Set col = Nothing ’ ... not realy 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

’ calculate the radius


Public Sub SetRadius()

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.

’ create a sphere in modelspace


Public Function Create(r As Integer, g As Integer, b As Integer) As Boolean

’ 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

’ setup the color value


Call col.SetRGB(r, g, b)

’ caculate the radius of the sphere


Call SetRadius

’ create the ACad3dSolid sphere object


Set s = ThisDrawing.ModelSpace.AddSphere(xi, rs)

’ assign the color to the sphere


s.TrueColor = col

’ every ok!
Create = True

E. Baeck
6.2. CLASS MODUL MASSES Page 55

End Function

6.2 Class Modul Masses

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

The class modul has only two attributes.

• The address of the center of mass object CoM.

• The address of the used collection List.

’ Container for our mass point objects

Public CoM As MassObj ’ Address of Center of Mass Object


Public List As Collection ’ Address of the Mass Object List / Container

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()

Set CoM = New MassObj ’ create the Mass Object


Set List = New Collection ’ create the List/Collection

End Sub

The method CreateRndMassesInCube creates a random point distribution in a cube. The


routines parameters are the following.

• MCount, the number of mass points to create.

• MMin, the minimum value of the mass distribution.

• MMax, the maximum value of the mass distribution.

• LBox, the edge length of the cube.

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

mrandom = mMin + (mMax − mMin ) · Rnd (6.2)

The random position in a cube with edge length L is given by


L
xrandom = − + L · Rnd (6.3)
2
After having calculated the random parameters a MassObj instance is created and the param-
eters are assigned. Then the instance is stored in the collection list using the Add function of
the collection.

’ Create random Mass Points in a Cube



’ MCount: Number of Masses to create
’ MMin : Minimum Mass Value
’ MMax : Maximum Mass Value
Public Sub CreateRndMassesInCube(MCount As Integer,
MMin As Double, MMax As Double,
LBox As Double)

Dim MObj As MassObj ’ Address of a mass object


Dim x(2) As Double ’ Position of the mass object (random)
Dim M As Double ’ Mass value (random)

’ initialize the random number generator


Call Randomize

’ loop over all mass points


For i = 1 To MCount

’ calculate the random mass value


’ Rnd : [0..1]
M = MMin + (MMax - MMin) * Rnd

’ calculate the random position


’ over all directions
For j = 0 To 2

x(j) = -LBox / 2# + LBox * Rnd

Next

’ Create the mass object


Set MObj = New MassObj

E. Baeck
6.2. CLASS MODUL MASSES Page 57

MObj.M = M
Call MObj.setX(x)
Call MObj.SetRadius

’ Add the pointer to the list/collection


List.Add Item:=MObj

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.

’ Create Spheres of all Mass Points

Public Sub CreateSpheres()

’ Address of a MassObj instance


Dim MObj As MassObj

’ Add spheres to the modelspace


For i = 1 To List.Count

’ get an item from list


Set MObj = List(i)

’ 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

’ write status to the command window


ThisDrawing.Utility.Prompt vbCr & vbLf & s

Next

End Sub

18.4.2011
Page 58 CAD in Civil Engineering / 2011

6.3 Frame Application

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.

6.3.1 EXCEL-Sheet, Input Section

To create our random mass point distribution we need the following input parameters.

• Number of mass points to create.

• Minimum mass value.

• Maximum mass value.

• Length of the cube region or diameter of the sphere region.

Figure 6.1 shows the excel sheet for the in-


put data. To be able to access to the in-
put data cells without the usage of global
row/column index values we have to introduce
range names. We use the following names
for the ranges: MNumber for the number of
the mass points, MassMin for the minimum
and MassMax for the maximum mass value.
Length is used as name for the region’s di-
mension.

Figure 6.1: Input Sheet for the Mass Point Appli-


cation

6.3.2 EXCEL-Sheet, Output Section

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.

• 1st column, the mass number starting from one,

• 2nd column, the mass’s random value and

• 3rd till 5th column, the mass’s random position.

E. Baeck
6.3. FRAME APPLICATION Page 59

Figure 6.2 shows the last input cell of the


sheets input section. With the title Output
the sheet’s output sections starts. The con-
tainer of the mass objects will be iterated from
the first to the last object. The objects data
are printed into the objects output line.

Figure 6.2: Output section of the EXCEL-Sheet

Figure 6.3 shows the footer region of the excel-


output. As control values we find the extrem
values of the random distribution (maximal
and minimal value of mass value and position)
and their mean values.

Figure 6.3: Output section of the EXCEL-Sheet,


Control Values

6.3.3 Sample, Step 1

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.

’ Create a random mass point distribution

Sub CreateSomeRandomMassPoints()

Dim MNum As Integer


Dim MMin As Double
Dim MMax As Double
Dim LBox As Double

’ 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

’ specify the filename


FileName = e.GetOpenFileName(
fileFilter:=”Excel-Inputfile (*.xls),*.xls”)

’ check if dialog is canceled


If FileName = ”Falsch” Then Exit Sub

’ Open the specified file


e.Workbooks.Open FileName:=FileName

’ get EXCEL-Sheet
Set s = e.Worksheets(”Masses”)

’ get EXCEL-Sheet input


MNum = s.Range(”MNumber”)
MMin = s.Range(”MassMin”)
MMax = s.Range(”MassMax”)
LBox = s.Range(”Length”)

’ Reset the modelspace


Call ResetModelspace

’ create the masses container


Set MList = New Masses

’ create mass distribution


Call MList.CreateRndMasses(MNum, MMin, MMax, LBox)

’ create spheres
Call MList.CreateSpheres

’ schließen der Data


e.ActiveWorkbook.Save
e.ActiveWindow.Close
e.Application.Quit
Set e = Nothing

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.

Figure 6.4: Distribution 1

6.3.4 Sample, Step 2

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 mass distribution


’>>
Call MList.CreateRndMassesInCube(MNum, mmin, mmax, LBox)

’ create spheres
Call MList.CreateSpheres(s)

’ close the input file


’>> close EVERYTHING
’ e.ActiveWorkbook.Save
’ e.ActiveWindow.Close

’ and quit the excel application


’ e.Application.Quit

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.

’ Create Spheres of all Mass Points


’ s: pointer to the excel-sheet

Public Sub CreateSpheres(s)

’ Address of a MassObj instance


Dim MObj As MassObj
Dim j As Integer

’ helper variables to calculate the


’ maximum and minimum values
Dim xmin(2) As Double
Dim xmax(2) As Double
Dim mmax As Double
Dim mmin As Double

’ ... sums
Dim xs(2) As Double
Dim ms As Double

’ row number for excel output


nRow = 1

’ Add spheres to the modelspace


For i = 1 To List.Count

’ get an item from list


Set MObj = List(i)

’ 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

’ - for the rest


Else
For j = 0 To 2
If MObj.x(j) < xmin(j) Then xmin(j) = MObj.x(j)
If MObj.x(j) > xmax(j) Then xmax(j) = MObj.x(j)
Next
If MObj.M > mmax Then mmax = MObj.M
If MObj.M < mmin Then mmin = MObj.M

End If

’ calculation of the sum values


For j = 0 To 2
xs(j) = xs(j) + MObj.x(j)
Next
ms = ms + MObj.M

’ next line
nRow = nRow + 1

Next

’ calculation of the mean values


ms = ms / List.Count
For j = 0 To 2
xs(j) = xs(j) / List.Count
Next

’ next line
nRow = nRow + 2

’ output of maximum values


s.Range(”output”)(nRow, 1) = ”Maximum”
s.Range(”output”)(nRow, 2) = mmax

18.4.2011
Page 64 CAD in Civil Engineering / 2011

For j = 0 To 2
s.Range(”output”)(nRow, 3 + j) = xmax(j)
Next

’ output of minimum values


nRow = nRow + 1
s.Range(”output”)(nRow, 1) = ”Minimum”
s.Range(”output”)(nRow, 2) = mmin
For j = 0 To 2
s.Range(”output”)(nRow, 3 + j) = xmin(j)
Next

’ output of mean values


nRow = nRow + 1
s.Range(”output”)(nRow, 1) = ”Mean value”
s.Range(”output”)(nRow, 2) = ms
For j = 0 To 2
s.Range(”output”)(nRow, 3 + j) = xs(j)
Next

’ set-up center of mass object


CoM.M = ms * List.Count
code = CoM.setX(xs)

’ create the sphere for the total mass


’ R G B
code = CoM.Create(0, 0, 255)

End Sub

E. Baeck
6.3. FRAME APPLICATION Page 65

Figure 6.5: Effective Mass

Figure 6.5 shows the result, calling the new version of CreateSpheres.

18.4.2011
Part IV

Exercises

66
7

Exam Projects SS10

7.1 General Notes

If you submit a exam project, the following components are unconditional needed.

• Report as paper version.

• Report as pdf version.

• dvb AutoCAD project file.

Within the report the following aspects are important.

• 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

7.2 Colored Hedgehog

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◦ .

Figure 7.1: Spherical Coordinates

The spheres colour should be interpolated from

• rgb(0,0,0) to rgb(255,0,0) for x from 0 to |x | = xmax 1 and

• rgb(0,0,0) to rgb(0,255,0) for y from 0 to |y| = ymax 2 and

• rgb(0,0,0) to rgb(0,0,255) for y from 0 to |z | = zmax 3 .

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

Set Operator, 25, 27


Single, 4 Byte Float, 11
spherical coordinates, 64
step, 8

Taskmanager, 32
ThisDrawing, 37, 45
ThisDrawing.ModelSpace, 45–47
timestamp, 41
now, 41
True, 55
TypeName, 46

UBound, 26
Utility object, 37

E. Baeck

You might also like