Está en la página 1de 154

Chapter1 Introduction

CHAPTER 1

INTRODUCTION

1.1 Introduction

In general, a Computer Aided Design (CAD) package has three components: a) Design,
b) Analysis, and c) Visualization, as shown in the sketch. A brief description of these
components follows.

a) Design: Design refers to geometric modeling, i.e., 2-D and 3-D modeling, including,
drafting, part creation, creation of drawings with various views of the part, assemblies
of the parts, etc.
b) Analysis: Analysis refers to finite element analysis, optimization, and other number
crunching engineering analyses. In general, a geometric model is first created and
then the model is analyzed for loads, stresses, moment of inertia, and volume, etc.
c) Visualization: Visualization refers to computer graphics, which includes: rendering a
model, creation of pie charts, contour plots, shading a model, sizing, animation, etc.

Design Analysis

Visualization

Components of Computer Aided Design


1

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-1


Chapter1 Introduction

Each of these three areas has been extensively developed in the last 30 years. Several
books are written on each of these subjects and courses are available through the
academic institutions and the industry.

Most commercial CAD packages (software) consist of only a single component: design
or analysis or visualization. However, a few of the vendors have developed an integrated
package that includes not only these three areas, but also includes the manufacturing
software (CAM). Due to the large storage requirement, integrated packages use either an
UNIX workstation or a mainframe platform, and not the popular PC platform. With the
improvement in PC computing speed, it’s only a matter of time before we see an
integrated package run on a PC. CAD has revolutionized the modern engineering
practice; small and large companies use it alike, spending several billion dollars for the
initial purchase or lease alone. CAD related jobs are high in demand and the new
graduates have advantage over their senior colleagues, as they are more up to date and
more productive.

In this course, we will limit our coverage to the design only. Those of you interested in
analysis area, look into the course ME 160 – Introduction to Finite Element Analysis.

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-2


Chapter1 Introduction

1.2 Computer Aided Manufacturing (CAM)


CAM is the next stage of CAD. A part created in CAD can be downloaded and
manufactured, without a human hand touching the part. The process is called CAM, and
involves CAD, Networking, and NC programming, as shown below.

CAD Networking

NC programming
Process planning
Inspection and simulation

Components of Computer Aided Manufacturing

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-3


Chapter1 Introduction

1.4 Concurrent Engineering


Concurrent Engineering is another powerful CAD concept that has evolved in the 90’s.
According to this concept, there is an instantaneous communication between the
designer, analyst, and manufacturing. Changes made at any of these work centers are
immediately passed on to the others and the product is modified without delay. Often, the
customer, management, and the marketing people join in and become part of the process.
Concurrent engineering saves the valuable time and helps get the product out in the
market quicker. Products that use to take years from the date of its concept to the actual
production now take only a few weeks, and the final product is better and cost-effective.

Some large organizations have invested in Rapid Prototyping process. In this process, the
part is created by a CAD package and downloaded into the rapid prototyping machine;
the machine immediately manufactures the part, using a plastic material. This is a good
example of concurrent engineering, sometimes referred as Art to Part concept.

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-4


Chapter1 Introduction

1.5 CAD/CAM History


The concept of CAD and CAM is relatively new. The usage is linked with the
development of computers. The actual application of CAD/CAM in industry, academia
and government is only approximately 30 years old. Formal courses in CAD and Finite
Element Analysis (FEA) were introduced in 1970’s. The major application thrust of CAD
came in 1980’s, with the availability of PCs and workstations. In its early stage of usage,
very few engineering companies could afford the expense of mainframe computers;
however, PCs and workstations have evolved into affordable and adequate platform to
support comprehensive CAD packages that initially were designed to run on the
mainframe platform. A brief history of the evolution of CAD/CAM, according to the
decade and the major CAD/CAM developments, is outlined below.

1960’s
• Development in Interactive computer graphics research
• Sketchpad system developed by Ivan Sutherland in 1962
• CAD term coined
• First major commercial CAD/CAM software available: CADAM by Lockheed, in 1965
• Bell Telephone’s - Graphics 1 remote display system developed

1970’s
• Application of CAM in government, industry and academia
• National organization formed
• Beginning of usage of computer graphics
• Turnkey system available for drafting
• Wireframe and surface modeling software became available
• Mass property calculation and FEA software became available
• NC tape generating, verification, and integrated circuit software became available

1980’s
• CAD/CAM used for engineering research and development
• New CAD/CAM theories and algorithms developed
• Integration of CAD/CAM
• Solid modeling software became available
• Use of PCs and workstation began

1990’s
• Concept of concurrent engineering developed
• Increased use of CAD/CAM on PCs and worksations
• Improvements in hardware and software

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-5


Chapter1 Introduction

1.6 CAD Hardware


There are basically two types of devices that constitute CAD hardware: a) Input devices,
and b) Output devices. A brief description follows.

1.6.1 Input Devices


These are the devices that we use for communicating with computer, and providing our
input in the form of text and graphics. The text input is mainly provided through
keyboard. For graphic input, there are several devices available and used according to the
work environment. A brief description of these devices is given here.

Mouse: This is a potentiometric device, which contains several variable resistors that
send signals to the computer. The functions of a mouse include locating a point on the
screen, sketching, dragging an object, entering values, accepting a software command,
etc. Joystick and trackballs are analogous to a mouse device, and operate on the same
principle.

Digitizers: Digitizers are used to trace a sketch or other 2-D entities by moving a cursor
over a flat surface (which contains the sketch). The position of the cursor provides a
feedback to the computer connected with the device. There are electrical wires embedded
in orthogonal directions that receive and pass signals between the device and the
computer. The device is basically a free moving puck or pen shaped stylus, connected to
a tablet.

Light Pens: Lockheed’s CADAM software utilized this device to carry out the graphic
input. A light pen looks like a pen and contains a photocell, which emits an electronic
signal. When the pen is pointed at the monitor screen, it senses light, which is converted
to a signal. The signal is sent to the computer, for determination of the exact location of
the pen on the monitor screen.

Touch Sensitive Screens: This device is embedded in the monitor screens, usually, in the
form of an overlay. The screen senses the physical contact of the user. The new
generation of the Laptop computers is a good example of this device.

Other Graphic Input Devices: In addition to the devices described above, some CAD
software will accept input via Image Scanners, which can copy a drawing or schematic
with a camera and light beam assembly and convert it into a pictorial database.

The devices just described are, in general, independent of the CAD package being used.
All commercial CAD software packages contain the device drivers for the most
commonly used input devices. The device drivers facilitate a smooth interaction between
our input, the software, and the computer. An input device is evaluated on the basis of the
following factors:
• Resolution 6
• Accuracy

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-6


Chapter1 Introduction

• Repeatability
• Linearity

1.6.2 Output Devices


After creating a CAD model, we often need a hard copy, using an output device. Plotters
and printers are used for this purpose. A plotter is often used to produce large size
drawings and assemblies, where as, a laser jet printer is adequate to provide a 3-D view
of a model. Most CAD software require a plotter for producing a shaded or a rendered
view.

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-7


Chapter1 Introduction

1.7 CAD Software


CAD software are written in FORTRAN and C languages. FORTRAN provides the
number crunching, where as, C language provides the visual images. Early CAD
packages were turnkey systems, i.e., the CAD packages were sold as an integrated
software and hardware package, with no flexibility for using second vendor hardware
(1970s and 80s). These systems were based on 16-bit word, and were incapable of
networking. The modern CAD software utilizes the open architecture system, i.e.,
software vendors do not design and manufacture their own hardware. Third party
software can be used to augment the basic CAD package. Most popular CAD package
will facilitate integration of the Finite Element Analysis and other CAD software from
more than one vendor. For example, IDEAS preprocessor can work with almost all the
FEA packages for pre and post analyses.

Networking is an important consideration in applications of CAD software. A model


created by one engineer must be readily accessible to others in an organization, which is
linked by a LAN or other means. The designer, analyst, management, marketing, vendor,
and others generally share a model. This is the concurrent engineering in action,
mentioned earlier.

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-8


Chapter1 Introduction

1.8 CAD Platform


In general, we can run CAD software on three different CAD platforms: Mainframe,
Workstation, and PC. When the CAD programs first became available, they could only
be run on a mainframe computer. However, as the PCs have become faster and cheaper,
almost all the CAD vendors have introduced a version of their CAD software that will
effectively run on a Pentium or higher computer. Currently, the most popular platforms
are PCs and Workstations. Popularity of Workstations stems from their ability to network
easily with other computers, and also, due to their large memory storage capability.
However, PC platform is still the most preferred medium for most engineers. Increasing
popularity of the PC platform can be attributed to several factors, including, total user
control, the speed, capability of storing large memory, ease of hardware upgrading and
maintenance, and the overall reasonable cost.

CAD PLATFORMS

MAINFRAME WORKSTATIONS PCs


Large Data storage Medium size data storage Limited data storage
Networked Networked Can be networked
Expensive Relatively inexpensive Inexpensive
Need interface language Runs on Unix Run on MS-Windows
No user control No user control User controlled
Good for Large corporations Good for small companies Good for all users

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-9


Chapter1 Introduction

1.9 CAD Evaluation Criteria


In the current CAD market, ProE and AutoCAD are arguably the most dominating CAD
software. AutoCAD is basically a 2-D program, with some capability to create 3-D
models, where as, ProE is a truly 3-D CAD package. Besides these software, there are
several other CAD software, listed in the previous section (Sec 1.3), that have sales
exceeding $100 millions. No one CAD package is suitable for all the CAD users in the
world. The product we are designing dictates the type of CAD package we need. A good
CAD package includes good software, as well as, a compatible hardware. Following is a
brief description of the general criteria for evaluating a CAD package.

Hardware: Most desirable features in a good hardware are:


• Open architecture
• High speed, large storage
• Compact size
• Inexpensive components
• Inexpensive upgrading

Software: In general, the most comprehensive software are written to satisfy almost all
the modeling needs of a modeler, consequently, the software tend to be very complex and
hard to learn. To create a simple model, we go through several unnecessary steps, and
lack the intuitiveness of a simple, straightforward program. ProE is a good example,
where we have to go through several layers of menus to create a simple solid. On the
other hand, if we were to use a simpler CAD program, the same solid can be created by
only a few simple commands. There are several other factors that we should consider
when evaluating software. Following is a brief description of these factors.

• Operating System: Unix or Windows/NT. PCs in general use Microsoft Windows,


where as, operating system for Workstations is Unix. For a large organization,
Workstations are preferable.
• User Interface: Most popular CAD software have menu driven commands, which is
preferable to the old system of non-menu driven, where user interface was completely
by responding to software commands. The most popular CAD programs work with
menu driven interface, with some input/action required through command prompts.
• Documentation and Support: Learning a software can be very difficult if the
software lacks good documentation. Documentation usually comes in the form of a
user’s manual, a tutorial book, commands manual, and on-line help. The recent trend
is to provide access to the above-mentioned documentation through the Internet, or
provide the manuals on a CD ROM. Some CAD vendors provide additional technical
support help through phone – ProE is a very good example of this type of support.
• Maintenance: Cost of the hardware and software upgrades can significantly impact
the small and medium size companies’ decision to choose one software over the
others. Most CAD vendors go through an upgrade, on the average, every two years.
Usually, hardware upgrade is not as frequent. 10

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-10


Chapter1 Introduction

• Modeling Capabilities: In, general, a CAD software can be classified as either a 2-D
or a 3-D program. If we were basically involved in 2-D drawings, any well
established 2-D software, similar to AutoCAD would suffice our needs. On the other
hand, if we need to create 3-D models and assemblies, we will be better off with a 3-
D molder – ProE, SOLIDWORKS, etc.
• Ease of Modeling: As a rule-of-thumb, a general, all-purpose type CAD software is much
more complex and difficult to learn than a special purpose CAD package.
• Interface with other CAD Packages and Data Transferability: A CAD package is used to
create models that will be used for analysis, manufacturing, or some other applications.
Therefore, a CAD software should be capable of transferring and accepting files from other
CAD or CAM programs, without this provision, the CAD program has only a very limited
use.
• Design Documentation: Besides creating a model, the software should be capable of
creating drawings, assemblies, dimensioning, various views (isometric, orthogonal, etc.),
labels and attributes, etc.

11

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-11


Chapter1 Introduction

1.10 Mechanical Engineering Applications of CAD


Following is a brief description of the applications of CAD in mechanical engineering.

• Two Dimensional Drafting: This is the most common use of a CAD package. 2-D
drawings are used for manufacturing a product.
• Report Generating: To generate reports and bill of materials. Spreadsheets and
word-processors can be linked to provide a report writing facility.
• 3-D Modeling: To create the wireframe, surface and solid models. The 3-D models
are for concept verification, manufacturing, FEA, etc.
• Finite Element Analysis: FEA package is used for pre-processing, analysis, and
post-analysis of structures. For this application, a CAD package contains both the
modeling and analysis modules.
• Manufacturing: manufacturing software is usually called CAM, and contains CAD
software as one of the components. CAM software provides capabilities of carrying
out 2 and 3-axes machining.

12

Lecture Notes © by R. B. Agarwal Computer Aided Design in Mechanical Engineering 1-12


1240 PROCEEDINGS OF THE IEEE, VOL. 69, NO. 10, OCTOBER 1981

ComputerDAided Design in Civil Engineering


STEVEN J. FENVES

Invited Paper

fications are still highly prescriptive, describing in detail exactly


what is to be done, or are highly procedural, defining a proce-
dure the result of which is deemed acceptable. The dispersion
of the civil engineering profession is further reinforced by local
and regional variations in building codes and by major differ-
ences among design specifications for, say,steel buildings,
highway bridges, and railroad bridges on one hand, and specifi-
cations for steel, concrete, and wood buildings on the other
I. INTRODUCTION hand.
A recent study by theGeneral Accounting Office [ 11 discus-
A . Nature o f Civil Engineering Profession ses the aforementioned factors and others which inhibit wider
acceptance of CAD in building design.

I N ORDER t o put computer-aided design (CAD) in civil


engineering intoproper perspective for apredominantly
electrical-engineering-oriented audience, three salient facts
about the civil engineering profession need t o be brought out.
Because of the great diversity of civil engineering, a single
survey article cannot cover CAD in a l l of its subdisciplines.
Thir paper will concentrate on structural engineering, which
First, civil engineering deals with a very broad range of p r o b encompasses the design of fixed structures, such as buildings
lems, including structures, foundations, transportation systems, and bridges. Design of fixed structures is closely allied t o the
environmental systems, and others. A simplified d e f i t i o n of design of other structures, be they automobile or aircraft bodies,
civil engineering is that it is concerned with the design, construc- ships or offshore structures. In fact,CAD in structural engineer-
tion and management of constructed facilities. Implicit in this ing has been strongly influenced by developments in the aere
definition is that civil engineers deal with large, one-of-a-kind space andshipbuildingindustries,where large organizations
and unique projects, and have noopportunity of building with single overall responsibility for design and manufacturing
“breadboard models” or prototypes. Consequently, civil could pioneer comprehensive CAD systems. In several key
engineers have to rely on analytical modeling, and by extension aspects ofCAD, there have also been influences from other
on CAD, possibly to a larger extent than other engineering fields, notably electrical engineering; some of these willbe
disciplines. highlighted later.
Second, civil engineering is highly dispersed. There are thou- B. Origins o f CAD
sands of design and construction f i s , either specializing in Notwithstanding the impediments described, civil engineers
particular technical disciplines or doing general work on a lim- have been early users of computers in design. Computer use
ited geographic basis. The separate responsibilities for design emerged in the late 1950’s in response to two major develop
and construction are often legally enforced,creatingmajor ments. First, the rapid expansion of the aerospace program
constraints to widespread, integrated CAD. Thus in publicly accelerated the development of new, powerful analysis tech-
financed construction awarded on thebasis of competitive bids, niques, t o be discussed in Section 11, predicated on the com-
all contractors bid on the same set of plans and project specifi- puter’s capability of handling large sets of discrete equations
cations. The designer’s database generated by CAD cannot be and requiring new, general approaches to modeling structural
passed on in computer-processableform to the contractor’s systems. Second, the equally rapid pace of design and construc-
computer-based project management system. tion of the interstate highway system introduced the need for
Third, as a direct result of the separation of responsibilities computer applications involving basically simple calculations
between the designer, constructor, owner and regulatory agen- (earthwork quantities, horizontal and vertical roadway align-
cies on a project, many of the constraints affecting design are ment, etc.) on large volumes of data. Thesedual trends of
external to the designer, embodied in the building codes, stan- using the computer’scapacity t o store andmanipulate very
dards and design specifications governing acceptability. While large models and its speed t o process large volumes of data are
there is a move towards performance-type design specifications, still the primary manifestations of the use of CAD in civil engi-
which prescribe only the requisite performance of the system, neering practice.
structure or component, many building codes and design speci- The progress of CAD in structural engineering is well docu-
mented in the seven Proceedings o f the Conference on Elec-
Manuscript received March 12,1981;revised May 12,1981. tronic Computation sponsored by the ASCE Structural Division
The authoris with the Department of Civil Engineeringand theDesign
Research Center, Carnegie-Mellon University, Schenley Park,Pittsburgh, Committee on Electronic Computation [2]-[8], and in jour-
PA15213. nals such as the International Journal o f Computers and Struc-

0018/9219/81/1000-1240$00.75 0 1981 IEEE


FENVES: CAD IN CIVIL ENGINEERING 1241

(a) (b)
Fig. 1. (a) Structure. (b) Network analog of (a).

tures and the International Journal for Numerical Methods in [ 91, [ 101 : the sum of the forces at joints is zero (equilibrium;
Engineering. equivalent to Kirchhoffs node law); the sum of distortions
(relative displacements) is zero in any closed loop (compatibil-
C. The Structural Design Process ity; equivalent to the mesh law); and, if the material is linearly
In order to put the remainder of the paper into context, the elastic, stress or force is proportional to strain or distortion
typical structural design process is briefly described. The pro- (Hooke’s law; equivalent to Ohm’slaw). If the loads are stat-
cess is not significantly different than that for the designof ically applied, structural analysis is conceptually no different
any engineering artifact or system,andcanbeconveniently from the analysis of a dc resistive network. If -linear elastic
subdivided into the following stages. behavior is assumed, the analogousnetwork is linear. Fig. 1
1) Preliminary design, in which the client’s functionalrequire- shows a simple frame structure and its network analog.
mentsandconstraintsare synthesized into apreliminary There are major differences, however. First, forces and dis-
concept. placements are vectors, ratherthan scalar quantities like current
2) Detailed design of the concept selected, which typically and voltage. For the planar structure shown, the load at any
involved several iterations between analysis and proportioning. joint is a vector consisting of a horizontal load, a vertical load
Analysis involves the determinationof the response of the struc- and a moment in the plane, and the displacement has a hori-
ture, in termsof internal forces, stresses and deflections, to the zontal, vertical and rotational component. Similarly, the force
loads imposed on it. Proportioning means selecting structural resultant in every member consistsof an axial force, atransverse
components (e.g., beams, columns, slabs ortheir respective (shearing) force and a bending moment. The elastic properties
subcomponents) such that they satisfactorily resist the forces of the member are specified by a 3 X 3 member stiffness (ad-
they are subjected to. As pointed out above, measures of satis- mittance)or flexibility(impedance)matrix. Thenumber of
factory performance may be largely specified externally by the vector components, or degrees of freedom, at each joint varies
applicable codesand design specifications.Significant devia- with structural type from 2 for planar trusses to 6 for space
tions between component properties assumed in the analysis (three-dimensional) frames. Thus a more direct analog is a
and those provided by proportioning necessitate a reanalysis. multiwire network. As a matter of fact, several early structural
The process iterates until the design is satisfactory or optimal, analysis programs relied on sparse matrixequation solvers
if an optimality criterion is available. Of course, there may be developed at the Bonneville Power Administration [ 11I and
global iterations involvingrevisionsof the overall structural elsewhere for transmission line analysis.
concept, and sub-iterations involving segments of the structure, A second difference is that the magnitude of the force and
or different analytical models, proportioning rules, or both. displacementvectorcomponentsdepends onthecoordinate
3) Preparation of design documents, namely thedesign draw- system used. Thus, to enforce equilibrium at a joint, all force
ings and project specifications describing the structure to be vectors have to be transformed into a common coordinate sys-
built. tem. Early structural modelsbased on a direct networkanalogy
This brief outline forms the basis for the presentation that attempted to divorce this geometric aspect entirely from pure
follows. The well-developedCAD applications,namelythose networktopologyby expressingall forceanddisplacement
supporting analysis, certain aspects of proportioning, and p r e p quantities in a single coordinate system [ 121, [ 131. This re-
aration of design documents will be discussed first. More prob- sulted in poorly conditioned equations, andless drastic geomet-
lematic areas, still subject to intensive research, arediscussed ric transformations are nowgenerally used.
last. The two standard network solution techniques, the node and
the mesh methods, have direct structuralanalogs calledthe stiff-
11. CAD TOOLS FOR ANALYSIS ness and flexibility methods, respectively. Structural analysts
use the stiffness (node) method almost exclusively, as it can be
Analysis of a mathematical model of a structure is governed fully generalizedand automated. By contrast,the flexibility
by physical laws not subject to the engineer’s interpretation. (mesh) method involves computational and conditioningprob-
It has, therefore, been the most readily implementable aspect lemsconsiderably more severe thanthe analogousnetwork
of CAD in structural engineering. problem of defining a spanning tree and corresponding basic
meshes, and is rarely implemented in CAD programsexcept
A . Mathematical Models for.very simple, specific structural types, such as beams con-
Many structures,such as trusses, framesand grids, canbe tinuous over several supports.
adequately modeled as an assemblage of one-dimensional ele- The basic structural analysis problem, then, is to generate and
ments connected or framed only at their ends. The establish- solve the matrix equation
ment of the analogybetweensuch framedstructures and
electrical networks goes back at least to Gabriel Kron’s work [KI {.I = {PI (2.1)
PROCEEDINGS OF THE IEEE, VOL. 69, NO. 10, OCTOBER 1981

hypervector of known joint loads, consisting of s u b


Stress t
vectors of loads at individualjoints;
hypervector of unknown joint displacements; Not t o scale

assembled structure stiffness matrix [a]t[k] [a];


unassembled member stiffness matrix, a diagonal hy-
permatrix consisting of the stiffness matrices of the Strain
individual members; (Elongation)
generalized incidence matrix, reflecting both the t o p Fig. 2. Typical streswttrain diagram of ductile material.
ology (connectivity) and the geometric transforma-
tions between structure (global) and member (local) are preferred. Damping is usually very small, of the order of
coordinate systems. 5 to 10 percent of critical,and thus the exact damping mecha-
The internal member forces can thenbe obtained by back sub- nism is not very important. Frequently, the mass matrix [MI is
stitution as modeled as a diagonal matrix of masses lumped at the nodes.
However, if the stiffness matrix [ K] is generated from a finite-
{Rl = [kl [a1 {ul (2.2) element model, the concept of consistent m a s matrices [ 161
where { R } is the hypervector of member force resultants. can be used to generate [MI using the same approximation or
Other effects on the structure, including loads applied di- shape functions as those used t o generate [Kl . For large-scale
rectly to membersandapplieddisplacements (e.g., thermal problems, condensation or substructuring is used to condense
strains, relative displacements due to lack of fit in erection, or out of (2.1) or (2.3) all “slave” or dependent degrees of free-
support settlements) can be handled by transforming all such dom, resulting in a reduced set of “master” or independent
effects to equivalent joint loads. degrees of freedom. For the static case, the condensation is
Essentially all the limitations introduced in the above struc- exact; for the dynamic case, an approximation whichpreserves
tural model can be relaxed. First, many structures and struc- the energy content is frequently used [ 171.
turalcomponentsarecontinuous,eitherintwodimensions Finally, equations (2.1) and (2.3) canbe extended to nonlin-
(e.g., plates and shells) or in three (e.g., thick-walled vessels, ear behavior. In structural engineering terminology, a distinc-
gravity dams). For such structures, or for the detailed modeling tion is commonly made between material nonlinearity, affecting
of discrete components, the Finite Element Method has come only the element submatrices [kl , and geometric nonlinearity
into universal use [ 141, [ 15 I. Finite element modeling sub- involving large displacements, which also affects the geometric
divides analysis into two phases. Intheelement phase,the terms in the incidence matrix [a]. Standard techniques, such
continuous model of a discretized region, thefinite element,is as Newton-Raphson, are used to solve the resulting nonlinear
converted by means of local approximation or shape functions algebraic equations (2.1) or differential equations (2.3).
into an equivalent model in terms of discrete variables, namely Many structural materials, such as mild steel and properly
the forces and displacements at the vertices of the finite ele- reinforced concrete, exhibitthe
load-deflectionbehavior
ment, yielding the element stiffness matrix[ke]. In the global sketched inFig.2. The traditional design methodology is to
phase, equation (2.1) is used to solve for the system displace select safety factors such that the working stresses due to the
ments. The only modification in (2.1) is that the incidence applied loads are of the order of 0.5 to 0.6 of the yield stress,
matrix is further generalized, since each finite element is inci- and then use the elastic analysis described above. An alternate
dent on more than twonodes. approach in design, or at least in determining the maximum
Second, there are many instances when dynamic, rather than limiting loadcarrying capacity, is to factor the applied loads
static, response is of interest. For conventionalcivil engineering by roughly the inverse of the safety factor,and perform a rigid-
structures, dynamic behavior is of concern where loading due plastic analysis, that is, seek the configuration subject to the
to wind, earthquake, moving loads or rotating equipment is constraints that equilibrium with the factored loadsis satisfied
significant. In many other typesof structures, suchas long-span and the yield stress is not exceeded anywhere. The analogous
bridges, radiotelescopes, offshore drilling
platforms, etc., network problem resembles the capacitated flow problem or
an all-transistor network [ 181.
dynamicbehavior is of paramount concern. Under dynamic
loading, equation (2.1) becomes B. Modeling Aids
[KI {.I+ [Cl {i}+ [MI = {fit)} (2.3) With the development of matrix structural analysisf i t , and
the finite-element method subsequently, the substantial com-
where
ponent of structural design dealingwith the analysisof the
[CI damping matrix; mathematical model of a structure has been largely relegated
[MI mass matrix; to computer programs. Attention has been increasingly shifting
{ u } , {ii} velocity and acceleration vectors, respectively; to input-output considerations, thatis, aids for thedesigner to
{fit)} vector of timedependent loads. describe the mathematical model and to interpret the results
The resulting problem is equivalent to a RLC network if veloc- obtained.
ities, rather than displacements, are made analogous to voltages. The first major trend has been the development of problem-
Standard techniques of time- and frequencydomain analysis oriented languages, in which the model to be analyzed is de-
applydirectly to (2.3). However, since the same structural scribed in a language similar to one that anengineer would use
elements provide the stiffness, damping and mass, integration incommunicatingwithanequallyknowledgeablecolleague.
schemes that preserve the secondsrder differential equation Fig. 3 shows a small structure and theinput necessary to
FENVES: CAD IN CIVIL ENGINEERING 1243

i 0
0
joint numbrrr

member
numbers

2 3 1
3 4 1
1 2 3
5 3 4
6 6 2
7 5 2
8 5 3
9 6 3
10 6 4
11 7 d
ii i i
mH3ER P R O P E R T I E S P. R I S W I T I C
1 AX 1.0
2AX 1.0
3 AX 1.0
4AX 1.0
5 AX 1.0
6 AX 1.0
7 AX 1.0
8 AX 1.0
9 AX 1.0
IO AX 1.0
1 1 AX L O
1 2 AX 1.0
nuuam of LOAOIXS 1
LOAOI’IGAPSITRCRI -
SEE S K f X d
TABULATE FORCES. J0ltlT DlS?LA:E
JOIN? L 0 A D S
I F Q R t E + ~ - l O . O . FORCE 2 5 . 0
6 FORCE
X 6.0
%LYE THIS ?ART

(a) (b)
Fig. 3. Sample problem description. (a) Structure. (b) Input.

describe it is the STRESS language, developed by Fenves et al. relieve the structural analyst of most of the tedious steps of
in 1962 [ 191. The relation of the input to the method devel- entering the mathematical model anddisplaying the computed
oped in the preceding section is to be noted: results, allowing him to concentrate on the two major functions
1) the TYPEcommand specifies the number andkind of of the modem analyst, namely modeling or idealizing a real
degrees of freedom involved; structure into a mathematical model to be analyzed, and inter-
2) the MEMBER INCIDENCES define the topology; preting and evaluatingthe computed response.
3) the JOINT COORDINATES, together with the MEMBER
INCIDENCES, specify all the geometricinformation
C. AnalysisPackages
needed to generate [a]. Matrix andfinite-elementprograms of practical usefulness
4)the MEMBER PROPERTIESprovided the information began to emerge in the mid-1960’s from universities and from
for generating the element [k] matrices. large organizations,primarilyin the aerospaceindustry. Pro-
The similarity of the input to contemporaneous electrical net- grams originating from universities, such as STRESS and later
workanalyzers,notably ECAP, is not coincidental, as the ICES-STRUDL [21] from M.I.T. or SAP [22] from the Uni-
writer’s work was heavily influenced by that of Branin [ 201. versity of California at Berkeley did not have the requisite s u p
The extensionof this mode of input tofinite elementanalysis port organizations to respond to user questions, fu program
is straightforward, requiring only an extended specification of bugs and otherwise maintain and enhance the program packages.
element incidences, and the specification of the element types Programs originating from industrial organizations frequently
and their corresponding parameters. could not be accessed by users outside these organizations.
The generation of the detailed input for a structure of even In the late1960’s, NASA commissioned alarge fiite-element
moderate size is highly repetitive and error prone. A host of system, called NASTRAN [ 231, to serve as a common analysis
preprocessors have been developed to handle most aspects of tool among NASA contractorsandotheraerospace users.
model generation, suchas generating the detailed topology and NASTRAN was specifically designed t o handle very large prob-
geometryand, in the caseof finiteelements,generating the lems, with up to 20 000 degrees of freedom. It contains both
finite element m3sh from a global description. Many prepro- a general high-level matrix language, DMAP, and a setof “fixed
cessors provide a graphicdisplay for visual verification and user formats” to deal with specificclasses of problems (e.g., linearly
modification before submitting ananalysis run. elastic dynamic analysis). Literally hundreds of other analysis
At the output end, postprocessors are generally used to per- packageshavebeen developed,some for in-houseuse,many
form additional calculations on the basic analysis results, such others forgeneral access through computer networks.
as computing stresses within elements, and for a wide variety Today, a verylarge fraction of structural analysis is performed
of graphic displays, such as deflected shapes, stress contours, on a few general-purposefiniteelementsystems,such as
etc.Thetype of displays produceddependon the graphic NASTRAN and STRUDL mentioned previously, ANSYS [ 241
devices available; the mostambitiousonescan display the and MARC [ 25 1. Each of these systems is supported by a staff
deformed structure inperspective, with colorscale proportional responsible for education and user training, “hot-line” trouble-
to stress intensity. shooting and continuous enhancement, either directly through
Overall, problemoriented languages and otherinteraction lease or license, or indirectly through computerutilities. Nota-
aids, together with graphic preprocessors and postprocessors, ble in this enhancement is the “downloading” of the systems
1244 PROCEEDINGS O F THE IEEE, VOL. 6 9 , NO. 10, OCTOBER 1981

to minicomputers such as the PRIME, NOVA, or VAX. Thus


many civil engineering organizations can now solve small prob- SECTION 1 . 5 ALLOMABLE STRESSES
lems completely ontheir in-house minicomputer, while for E x c e p ta sp r o v i d e di nS e c t s . 1.6,1.7,1.10, 1.11,
large problems the interactive preprocessing is done in-house, 1.16.4,and i n P a r t 2 , a l l components o f t h e s t r u c t u r e
s h a l l be so p r o p o r t i o n e dt h a tt h es t r e s s ,i nk i p sp e r
the debugged model is shipped for processing at a computer s q u a r ei n c h ,s h a l ln o te x c e e dt h ef o l l o w i n gv a l u e s ,
e x c e p ta sr o u n d e do f fi nA p p e n d i x A . See Appendix 0
utility, and thereturned resultsinteractivelypostprocessed f o ra l l o w a b l es t r e s s e sf o rw e b - t a p e r e d members.
locally. Theimportantpoint is that all problems can be
described in the same “language,” without concern as to where 1.5.1 S t r u c t u r aSlt e e l
the processing will be done. ... .
All commercial packages provide essentially the same set of 1.5.1.3 Canpression
basic facilities, e.g., linear analysis, using a standard library of
1.5.1.3.1 On t h e gross s e c t i o no fa x i a l l yl o a d e d
one- , t w e , a i d three-dimensional finite elements. Beyond compression members whose cross s e c t i o n s m e e t t h e
these capabilities, the packages tend to concentrate onspecific p r o v i s i o n so fS e c t . 1.9, when Kl/r, t h el a r g e s t
effectiveslendernessratioof anyunbracedsegmentas
behavior areas (e.g., aeroelasticity versus couplednonlinear d e f i n e di nS e c t .1 . 8 ,i sl e s st h a n C :
structural thermal problems), specific elements (e.g., shells of
revolution versus thick-walled pipes), or specific application ( K l / Fr ) ‘
classes, such as reactor vessels or offshorestructures. Users 1 - 7 Y

frequently select particular packages on the basis of familiarity F = 2cC (1.5-1)


with input preparation and general access convenience, rather
than specific program capabilities or relative efficiencies. A
notable development in allowing users t o move away from
constraints of specific packages is the emergence of general pre- where
and postprocessors such as UNISTRUC [261 or FASTDRAW
1.5.1.3.2 On t h e g r o s s s e c t i o no fa x i a l l yl o a d e d
[ 2 7 ] . With these systems, the user can interactively build or compression members, when Kl/r exceeds C-:
c
modify a modelindependent of the analysis package t o be used.
Whenever an analysis is need, the user issues a single command, (1.5-2)
such as “NASTRAN” or “ANSYS,” and the preprocessor gen-
erates the model description in the input formatof the desired 1.5.1.3.3 On t h eg r o s ss e c t i o no fa x i a l l yl o a d e d
bracingandsecondary members, when l / r exceeds120:
package. Similarly, the resultsofany analysis package sup- E Fs[by
Fonnula
(1.5-1) or 1.5-211
ported by the postprocessor can be returned and interactively ‘as = a
1
manipulated and displayed. 1.6 --
200r
( I .5-3)

111. CAD TOOLSFOR PROPORTIONING


AND PREPARATION 1.5.1.3.4 On t h e g r o s s a r e a o f p l a t e g i r d e r s t i f f e n e r s :
OF DESIGN DOCUMENTS Fa = 0.60F
Y
A . Proportioning
1.5.1.3.5 On t h e web o f r o l l e d shapes a t t h e t o e o f
Proportioning, as defined in Section I-C involves selecting t h ef i l l e t( c r i p p l i n g , see S e c t . l . 1 0 . 1 0 ) :
structural componentsso that they resist the forces determined Fa = 0.75F
from analysis, subject t o the designer’s intent as well as the Y
constraints of the applicable codes and design specifications. Fii. 4. Sample design provision (reproduced from 28).
To illustrate the problems involved in developing CAD tools
for this phase of design, Fig. 4 is a reproduction of a segment is acceptable or not. Unless one wants to do design by blind
of thecurrent, universally accepted design specification for “trial-anderror,” iterating on inequality (3.1) until a satisfac-
structural steel for buildings [ 281. The numerous cross refer- tory or optimal column is found, one has to convert the speci-
ences to other sections for exceptions or furtherd e f i t i o n are fication provision into a design procedure. But “design” means
worth noting. Notable by their absence are cross references to vastly different things at different stages of the process; con-
other provisions which also determine the acceptability of a ceivably every one of the variables AB, r, 2, K, and F, could
compression member, or to other needed defmitions (such as become the unknown t o be solved for so that inequality (3.1)
the definition of the term “gross area” in the first sentence of is satisfied. Furthermore, “design style” may enter; for exam-
Section 1.5.1.3.1 of the Specification). ple, many designers try to stayaway from very slender columns
The developer of a CAD program for the proportioning of governed by provision 1.5.1.3.2 of the AISC Specification
columns according to the Specification must first collect all because of their obvious inefficiency and other undesirable
the un-cross referenced applicable provisions, interpret them, effects. Many other decisions representingan organization’s
and thencode them in someprocedural language. But the design style enter the proportioning process, including economic
problem is deeper than that. The provision, as written, is a considerations; for example, should the column be made of a
checking tool, not a design tool. With the axial force Px deter- standard rolled structural shape, or built up bywelding together
mined from analysis, once a column with gross agea Ag, radius flat-plate elements.
of gyration r and effective length Kl has been selected, and the In summary, CAD tools forproportioning must, by necessity,
material yield stress F, is established, it is easy to check which incorporate assumptions and limitations specific to theindivid-
subprovision applies and whether the inequality ual organization’s mode of design. Thus an interesting paradox
emerges. In software engineering, the value of utility programs
px
fa = -<Fa (3.1) is measured by their portability, that is, how easily they can be
At? transplanted t o a new environment. In structural engineering,
is satisfied or not, denoting whether the trial column selected at least, the measure of the design program’s value is just the
FENVES: CAD IN CIVIL ENGINEERING 1245

reverse: if the programtrulyreflects the design style of the drawings and project
specifications. Where organizational
originating organization, it is bound to fail when used by an- arrangements permit direct transfer of information, such as in
other organization, in that it may yield results in variance with designsonstruct or “turnkey” contracts, thecomputer-process-
that organization’s assumptions and design style. able design data are used directly for the production of bills of
Notwithstanding the difficulties sketched above, proportion- materials, more detailed “shop drawings” and other construc-
ing and detail design programs have been developed and are tion, management, fabrication and erection applications inclu-
being routinely used for most aspects of structural design. For ding, in a fewcases, numerically controlled (NC) manufacturing
many simple classes of structures, such as transmission towers, applications, such as cutting, bending, bundling and labelling
industrial buildings, and short- to medium-span bridges, special- of reinforcing bars.
purpose programs incorporating both analysis and proportion-
JY. RESEARCH AREAS
ing are in wide use. While these programs provide the obvious
benefits of fasterresponsetime, more detailedand realistic There is continuing research and development to improve and
modeling, and capability of exploring more alternatives, they extend all of the CAD tools discussed previously. Particularly
all suffer from a lack of generality and from the fact that the in the area of analysis, there are vast areas on ongoing research
design specification provisions incorporated in them are deeply in order to extend finite element methods to larger and larger
embedded in the program code, thus making it expensive to classes of structural problems, notably for nonlinear behavior
update them to conform to changes in the specifications. Ways (fracture, fatigue, large displacements), and coupled problems
to overcome thislatter Limitation are discussed in SectionIV-C. (thermal,acoustical,aerodynamic, soil-fluid structure inter-
action, etc.). Similar strides arebeing made in computer
B. Preparation of Design Documents graphics and man-machine interaction studies in order to im-
The final output of the design process consists of design or prove the “man-machine symbiosis” in design.
contract drawings and project specifications. The production Thissectionbriefly describes anumber of potential CAD
of both of these is time consuming, tedious, and highly error areas which are still primarily in the research stage and have
prone. A wide variety of CAD tools are in general use for both not yet reached significant practical use.
of these activities. A . Synthesis
The preparation of contract drawings for a building or other Computer-aided synthesis, that is, the generation of an initial
structure is a typical computer-aided drafting application, and configuration from a description of functional requirements is
manyturnkeydrafting systemsoffer specialized menusfor still in its infancy in structural engineering. A literature search
structural and architectural drafting. One of the main advan- for this article did not reveal a single example comparable to
tages of such systems is their ability to superimpose multiple the chemical engineering flow sheet synthesis described in the
“layers” of graphical information, e.g., the structural, architec- companion article byWesterberg [ 3 11.
tural, mechanical and electrical subsystems within a building. There are a number of reasons for this lack. First, in struo
Many potentialspatialconflictscanthusbedetectedand turessuch as buildings, the primaryfunctionalrequirements
corrected. deal withspace,circulation, lighting, environmentalcontrol,
Stand-alone drafting systems require that all input be manu- etc., so that the purelystructuralconsiderations of strength
ally entered. Many organizations have made strides in integra- and stiffnessseldom govern. Second,structural engineers do
ting design and drafting programs, so that the design informa- not seem to deal with as many distinct possible alternatives as,
tion can be directly transferred to the drafting system. On the say, circuit designers; there are only a few classes of structural
otherhand,many of the special-purpose design programs configurations to choose from in designing a tall building or a
discussed inSection 111-A canproduce designdrawings as a bridge. Third, the use of CAD itself, with the opportunity to
postprocessing step, bypassing a separate drafting system. analyze rapidly and inexpensively any proposed structural con-
Thepreparation of projectspecifications is not normally figuration, has removed some of the impetus to use computer-
considered a CAD application. The traditional manual nlethod based tools to generate candidate configurations. Nevertheless,
is to use “scissors and paste” to compose a project specification research continues in the applications of artificial intelligence
out of standard paragraphs and special provisions for thepartic- and synthesisconceptsfrom other disciplines to structural
ularproject. A number of programscombining text editing design.
and text file retrieval are available to produce project specifi-
cations by merging and editing stored master specification pro- B. Optimization
visions [ 291, [30]. The output is directly suitable for repre Unlike synthesis, structural optimization has been an active
duction. While this has been a very popular application (for area of research for over 20 years[ 321 -[34]. The optimization
some small civil engineering firms, the only CAD application), problem based on elastic behavior may be stated as:
it can be criticized on conceptual grounds. The finished, neatly Minimize W(x) (3.2a)
formattedoutput consists of 95-percentstandard provisions
subject to:
(“biolerplate”)and
5-percent
project-specific
information,
without any clue to guide the contractor in finding the signifi- [K(x)l { u } - {P} = (0) (3.2b)
cantor unusual special requirements.Fromaninformation
theory standpoint, theseprograms take the small amount of
Lf} = [H(x)l
[k(x)l [a1 {.I Q {F} (3.2~)
information or “signal” and submerge it into the vast amount where{x}are the designvariables (typically,element size
of “white noise.” At least one of the specification editing sys- parameters), c f } theactual stresses, and { F } the allowable
tems now provides the option of printing a distinguishing mark stresses. The equality constraints are recast from (2. l), and the
on the margin next to thespecial provisions. inequality constraints on the elementstresses are obtained from
As indicated in the Introduction, the responsibility of many (2.2) and the generalization of inequality (3.1), [H(x)] being
design organizations terminates with the production of design a modulus matrix which converts element forces (axial, shear
1246 PROCEEDINGS OF THE IEEE, VOL. 69, NO. 10, OCTOBER 1981

and moment) into stresses. Plastic analysis, introduced in S e e


tion 11-A, is inherently a mathematical programming formula- Y N
tion (maximize theloadsubject to equilibriumandplastic
capacity constraints) which can readily be converted to design
(minimizeplasticcapacitiessubject to equilibriumwith the
factored loads) [ 181. Formula
x
Structural optimization can be further subdivided into three (1.5-1)
classes of increasing mathematical difficulty:
1) parameter optimization, in which only element sizes are
design variables, geometry and topology being fixed;
2) geometry Optimization, in which the coordinates of the x Formula
(1.5-2)
joints are also design variables, the topology staying fmed;
and
3) configuration optimization, where the structural configu-
ration,andtherefore, thetopology, is also includedin

1
the design variables.
A large number of mathematicalprogrammingtechniques
have been applied to thefmt two classes of problems. The third
class, which begins to approach synthesis, has been approached Fig. 5. Decision table for main members, Specification Sections
by zero-one programming methods [35]. 1.5.1.3.1 and 1.5.1.3.2.
The practical application of optimization has been hampered
by three factors. First, in structures,as in electrical engineering, The current practice of having each organization or program
it is difficult to develop objective(cost)functions that are developer perform the above two steps manually is not only
both realistic andmathematicallytractable.Themathemati- wasteful, in terms of duplication of effort, but may result in
cally simplest objective function, that is, the volume or weight serious errors if the developer’s interpretation is not thoroughly
of material (sum of length times area of members) is a patently checked.Furthermore,thesubstantialinvestment ofdesign
unrealistic cost function in an economybased on relatively low organizations in CAD programs based on current specifications
material costs and high labor costs. A more realistic cost func- have a negative effect on theorganizations’ willingness to adopt,
tion would include such considerationsas connection and detail or conform to, revisions of these specifications.
costs, cost of erection, etc., but these factors are difficult, if The author and his co-workershave addressed phase 1 by
not impossible, to obtain whendesign responsibility is com- using decision logic tables, or decision tables for short,to repre-
pletely divorced from construction responsibility. sent rigorously the intent of the specifications [36], [37]. Fig.
Second, the behavior or inequality constraints in ( 3 . 2 ~ )in- 5 is a decision table representation of the first two paragraphs
volvedesign specification provisions,which, as discussed in of Fig. 4. It can be seen that thereis one condition(Kllr < Cc),
Section 11-C, may be nonlinear or even discontinuous. Admit- two possible actions (the two formulas for Fa) and two rules,
tedly,foroptimizationpurposesonecanapproximate the each specifying the value of the condition (yes or no) that
specification constraints by mathematically simpler functions, determines which formula is to be used (shown by the X‘s).
but the optimum design must still be checked against the speci- The entire paragraph of Fig. 4 can be represented by the larger
fication constraints, andpossibly reproportioned. decision table shown in Fig. 6. The entry M (for minus) means
Third, parameters of structural components, especially steel, &I implied no: if the member type is muinrit is implied that it
are more realistically treated as discrete, rather than continuous is not one of the other three types addressed by the provision.
design variables. A number of discrete programming approaches The additional column in the figure, labelled ingredients, lists
have been presented [35], but their practical applications are the variables needed to evaluate the terms in the condition or
rare. The “ultimate” structural optimization problem, incorpo- action. Specifications can then formally be represented as net-
rating both discrete components and configuration optimizationworks of decision tables: the ingredients are either basic data
wouldbebased on zero-one programming, with design vari- (such as length I or yield stress F,,) or derived data output by
ables xii defined as: other decision tables (such as the factor K ) . The value of Fa
generated by the table shown becomes, in turn, an ingredient
1, if available structural shape i is used in of a higher level table, such as a table representing the result of

{
xij = possible member
0, otherwise.
location j

C. Representation of Design Specifications


inequality (3.1).
Decision tables have been found to be an ideal representa-
tional tool, from which application programs can be generated
either by manual codingor directly by preprocessors which ac-
As indicatedrepeatedly in this article,constraints arising cept decision tables as input. They have also been used as tools
from design specifications ubiquitously affect CAD tools for in the specification writing process, assisting specification de-
structural engineering. There are two distinct phases in incor- velopers in testing that the proposedprovisions are clear, com-
porating provisions such as those in Fig. 4 into CAD programs: plete and unambiguous [ 381 . Current research work addresses
1) interpreting the provisions and converting them into pro- the second phase above, namely converting the checking tables
grammable processing steps; automatically intodesign tools, by symbolically solving for the
2) converting the passive conformance checking provisions constraints on the designated design variables as a function of
into an active design sequence. the values of known data [39].
FENVES: CAD IN CIVIL ENGINEERING 1247

F by 1 . 5 - 1 X ’ x i
I
j
, I l k l r E F
Y
C
C
I
Fa by 1 . 5 - 2

Fa by 1 1. 5. 5- 3- 1, 11 j ( x k l r E F
Y
C
C
I
F- by 1 . 5 - 3 , 1 . 5 - 2 /j I X I I k l r E
Fa = ,130F X F
Y Y
F = .75 F X F
Y 1 I 1 Y

Fa.6. Decision table for Specification Section 1.5.1.3.

D. Databases Thus a major research and educationissue in civil engineering


Civil Engineering organizations have typically proceeded by is that of developing or adapting software development meth-
developingindividual, stand-alone CAD programsfirst,and odologies applicable to such a widely dispersed profession. The
then integrating these programsthrough common interface files payoff for such efforts is very high; precisely because of the
or databases. In many of the larger design firms, this integra- dispersion and dependence on regulatory bodies for approval,
tion has proceeded to the point where a substantial portion of the need for testing, verification and certification of CAD tools
the design information is maintained in a database, with appli- is probably even higher in civilengineering than in other
cation programs, such as those for analysis, proportioning and disciplines.
drafting, acquiring the common data from, andreturning their
V. CONCLUSIONS
results to, the database. In design-andconstruct or “turnkey”
organization, the database is extended into management and By all measures, CAD applications have become an indispens-
manufacturing applications as well. able andirreplaceableingredient of all aspects of civil engi-
The practical and research issues of engineering design data- neering practice. With CAD tools, civil engineers can be more
bases are explored in the companion article by Eastman [40]. responsive to their clients’ needs by exploring more alternatives,
It suffices to state here that full integration of CAD through by using more comprehensive analytical models, and by reduc-
common databases in civil engineering is hampered by the frag- ing the time and cost of detailed calculations. Being engineers
mentation of responsibilities both horizontally (amongpartici- worthy of thattitle, civil engineershave adaptedand even
pating design professionalsinseparatefunctions,such - _ ~
as optimized a revolutionarynew tool to thespecific circumstances
architectural, structural, mechanical and electrical design of a andmode of operation of their profession. Applications of
building) and vertically (among planning, design and construc- CAD will undoubtedly continue to expand in both depth and
tion activities). By the same token, however,integration breadth, but they will continue to be conditioned by the orga-
through such databases could provide one of the most signifi- nizational structure, diversity and dispersion of the profession.
cant increases in design productivityandefficiency. As the
recent activities in distributed databases show,it is operationally REFERENCES
possible to link databases residing on separate computers into [ 11 “Computer-aidedbuildingdesign,”Rep. LCD-78-300, U.S.Gen-
a network. e_al Accountkg Office! W-assgton, DC, 1978.
[ 2 ] Proc. ASCE Con$ ElectronicComputation (Kansas City, MO),
E. Software Engineering Tools 1958.
[ 3 1 h o c . 2nd ASCE Confi Electronic Computation (Pittsburgh, PA),
In the past ten years, software engineering has emerged as a 1960.
discipline separatefromcomputer science. Unfortunately, [ 41 Proc. 3rd ASCE Conf. Electronic Computation. Also published
in J. Structural Div., vol. 89, no. ST4, 1963.
neither the toolsof software engineering nor software develop- [ 5 1 h c . 4th ASCE Con$ Electronic Computation. Also published
ment management techniques have yet made major impact on in J. Structuml Div., vol. 92, no. ST6, 1966.
the manner in which civil engineering CAD tools are developed [a] Roc. 5th ASCE Con$ Electronic CompudPtion. Also published
in J. StructuralDiv., vol. 97, no. ST1, 1971.
and maintained. This is again a direct result of the dispersion (71 Roc. 6th ASCE Con$ ElectronicComputation. Also published
of the profession into many small organizations. In most such in J. Structural Div., vol. 101, no. ST4, 1975.
[ 8 1 Roc. 7th ASCE Confi Electronic Computation. (St. Louis, MO),
organizations, application software development is the respon- 1979.
sibility of a very small group (sometimes one individual, who [ 9 I G. Kron, “Equivalent circuits of the elastic field,” J. Appl. Mech.,
is also responsible for the operation of the in-house computer vol. 12, p., 221, 1945.
[ 101 -, “Solving highly complex elastic structures in easy stages,” J.
or terminal). These small groups can neither implement man- Appl. Mech., 22, p. 235, 1955.
agement techniques such as the “lead programmer” concept, [ 11 1 N. Sato and W. F. Tmney, “Techniques for exploiting the sparsity
of thenetworkadmittancematrix,” ZEEE Trclm. Power App.
nor do theyhave the opportunity to learn and practice modem Syst., v0l.P.M-86, p. 1449, 1963.
software development skills. [ 121 B. Langefors, “Analysis of elastic structures by matrix transfor-
1248 PROCEEDINGS OF THE IEEE, VOL. 69, NO. 10, OCTOBER 1981

mationwith special regard to semimonocoque structures,” J. Douglas Automation Co., 1978.


AeronmcricalScL, vol. 19, p. 451, 1952. I281 Specification f o r the D e s i g n , Fabrication and Erection of Struc-
[13] S. J. Fenves and F:H. Branin, Jr., “Nekork-topological formu- tural Steel for Buildings. New York, NY: American Institute of
lation of structural analysis,” J. StructumlDfv. (ASCE),vol. Steel Construction, 1978.
89(ST4), pp. 483-514, 1963. [ 2 9 ] E. S. Neely, Ir., “Construction specification preparation with the
[ 141 R.H. Gallagher, Finite Element AnaIysis-Fundamenrals. Engle- EDITSPEC system,” Rep. P-84, U.S. h y Construction Eng.
wood Cliffs, NJ: Prentice-Hall, Inc., 1975. Res. Labs., Champaign, IL, 1977.
[ 151 0. C. Zienkiewicz, The FiniteElementMethod. New York: I301 SPEC Reference Manual. Dayton, OH: Automated Procedures
McGraw-Hill, 1977. for Engineering Consultants, Inc., 1975.
[ 161 J. S. Archer, “Consistent m a s matrix for distributed systems,” [31] A. Westerberg, this issue, pp. 1232-1239.
J. Structural Div. (ASCE), vol. 89(ST4), pp. 161-174, 1963. [32] Z. Waaiutynski and k Brandt, “The present state of knowledge
[ 171 R. J. Guyan, “Reduction of stiffnessand mass matrices,”J. AZAA, in the field of optimum design of structures,” AppL Mech. Rev.,
vol. 3, p. 380, 1965. V O ~ .16, pp. 341-350, 1963.
[ 181 S. J. Fenves and A. Gonzalez-Caro, “Network-topological formu- [33] C.Y. Sheu and W. Prager, “Recentdevelopments in optimal
lation of analysis and design of rigid-plastic framed structures,” structural design,” AppL Mech Rev., vol. 21, pp. 985-992, 1968.
Znt. J. Numer. Meth. Eng., vol. 3, pp. 425-441, 1971. [34] V. B. Venkayya, “Structuraloptimization: A review and some
[ 191 S. J. Fenves, R.D. Logcher, and S. P. Mauch, STRESS-A User’s recommendations.” Znt. J. Numer. Meth. Enx.. - . vol. 13, pp. 203-
Manual. Cambridge, MA:M.LT. Press, 1964. 228,1978.
(20) F. H. Branin, Jr., “Machine analysis of networks and its applica- [ 3 5 ] G. Maier, “Limit design in the absence of a given layout,” in
tions,” Tech. Rep. 855, IBM Dev. Lab., Poughkeepsie, NY, 1962. Gallagher and Zienkiewicz, Eds., Optimum Structural Design.
[21] R. D. Logcher, et al., “ICES STRUDL-I, The structural design New York: Wiley, 1973.
language,” M.I.T., Cambridge, MA: Dep. Civil Eng., 1967. (361 S. K. Goel and S. J. Fenves, “Computer-aided processing of
[22] K. J. Bathe, E.L. Wilson, and F. E. Peterson, “SAP-IV-Astruc- design specifications,” J. Structural Div. (ASCE), vo. 97, (STl),
tural analysis program for static and dynamic response of h e a r pp. 463-479,1971.
systems,” EERC Reu. 23-1 1. Univ. California. Berkelev. 1973. [37] W. Rasdorf and S. J. Fenves, “Design specification representation
[23] C. W. McCormick, NASTRAN User’s Man&‘, Tech. R e p SP-222 and analysis,” in Roc. 2nd ASCE Con$ Computing in Civil En@
[24]
. -,. N A S A, 1972.
101). ~~~~~ ~- --
G.J. DeSalvo and J. A. Swanson, ANSYS User’s Manual. Hous- [38]
nerring, up. 102-111, 1980.
S. J. Fenves and R:N. Wright, “Therepresentation and use of
ton, PA: Swanson Analysis Systems, Inc., 1979. design specifications,” Tech Note 940, National Bureau of Stan-
[25] MARC User Information Manu&. Palo Alto, CA: MARC Analy- dards, Washington, DC, 1977.
sis Research Corp., 1971. [39] N. M. Holtzand S. I. Fenves, “Using design specifications in
[26] UNZSTRUC ZZ Reference ManuaL Minneapolis, MN: Control design,” in R o c . 2nd ASCE Con$ Computing in CfvU Engineer-
Data Corporation, 1979. ing, PP. 92-101,1980.
[27] FASTDRA W / 3 Reference Mmud St. Lou& MO: McDonnell- [40] C. Eastman, this issue, pp. 1249-1263.
IV
CONTENTS

Chapter 1 Introduction to Excel VBA 1

Chapter 2 Working with Variables in Excel VBA 7

Chapter 3 Using Message box and Input box in Excel VBA 16

Chapter 4 Using If….Then….Else in Excel VBA 25

Chapter 5 For……Next Loop 32

Chapter 6 Do……Loop 40

Chapter 7 Select Case.........End Select 44

Chapter 8 Excel VBA Objects Part 1–An Introduction 46

Chapter 9 Excel VBA Objects Part 2 –The Workbook Object 55

Chapter 10 Excel VBA Objects Part 3 –The Worksheet Object 60

Chapter 11 Excel VBA Objects Part 4–The Range Object 66

Chapter 12 Working with Excel VBA Controls 75

Chapter 13 VBA Procedures Part 1-Functions 86

Chapter 14 VBA Procedures Part 2-Sub Procedures 96

Chapter 15 String Handling Functions 99

Chapter 16 Date and Time Functions 102

Chapter 17 Sample Excel VBA Programs 109


1

Chapter 1

Introduction to Excel VBA

1.1 The Concept of Excel VBA

VBA is the acronym for Visual Basic for Applications. It is an integration of the
Microsoft's event-driven programming language Visual Basic with Microsoft Office
applications such as Microsoft Excel, Microsoft Word, Microsoft PowerPoint and
more. By running Visual Basic IDE within the Microsoft Office applications, we can
build customized solutions and programs to enhance the capabilities of those
applications.

Among the Visual Basic for applications, Microsoft Excel VBA is the most popular.
There are many reasons why we should learn VBA for Microsoft Excel, among them
is you can learn the fundamentals of Visual Basic programming within the MS Excel
environment, without having to purchase a copy of Microsoft Visual Basic software.
Another reason is by learning Excel VBA; you can build custom made functions to
complement the built-in formulas and functions of Microsoft Excel. Although MS
Excel has many built-in formulas and functions, they are not enough for certain
complex calculations and applications. For example, it is very dificult to calculate
monthly payment for a loan taken using Excel's built-in formulas, but it is relatively
easier to write VBA code for such calculation. This book is written in such a way that
you can learn VBA for MS Excel at your own pace.

You can write Excel VBA code in every version of Microsoft Office, including MS
Office 97, MS Office2000, MS Office2002, MS Office2003, MS Office XP , MS Office
2007 and MS Offce 2010. By using VBA, you can build some very powerful tools in
2
MS Excel, including financial and scientific applications that can perform financial
calculations and programs that can perform statistical analyses.

1.2 The Visual Basic Editor in MS Excel

There are two ways which you can start VBA programming in MS Excel. The first is
to place a command button on the spreadsheet and start programming by clicking the
command button to launch the Visual Basic Editor. The second way is to launch the
Visual Basic Editor by clicking on the Tools menu then select Macro from the drop-
down menu and choose Visual Basic Editor. Lets start with the command button first.
In order to place a command button on the MS Excel spreadsheet, you click the View
item on the MS Excel menu bar and then click on toolbars and finally select the
Control Toolbox after which the control toolbox bar will appear, as shown in Figure
1.1. ,then click on the command button and draw it on the spreadsheet, as shown in
Figure 1.2.

Figure 1.1: Displaying Control Toolbox in MS Excel.


3

Figure 1.2: The Command Button in Design Mode

Now you select the command button and make sure the design button on the far left
of the control toolbox is depressed. Next, click on the command button to launch the
Visual Basic Editor. Enter the statements as shown in figure 1.3. Let’s write out the
code here:

Example 1.1

Private Sub CommandButton1_Click ()

Range (“A1:A10).Value=”Visual Basic “

Range (“C11”).Value=Range (“A11”).Value +Range (“B11”).Value

End Sub
4
The first statement will fill up cell A1 to cell A10 with the phrase "Visual Basic" while
the second statement add the values in cell A11 and cell B11 and then display the
sum in cell C11. To run the program, you need to exit the Visual Basic Editor by
clicking the Excel button on the far left corner of the tool bar. When you are in the MS
Excel environment, you can exit the design mode by clicking the design button, then
click on the command button.

Figure 1.3: The Visual Basic Editor IDE in MS Excel

Running the above VBA will give you the output as shown in Figure 1.4
5

Figure 1.4:

1.3 The Excel VBA Code

Writing Excel VBA code is almost exactly the same as writing code in Visual Basic,
which means you have to use syntaxes similar to Visual Basic. However, there are
codes specially designed for use in MS Excel, such as the use of the object or
function called Range. It is the function that specifies the value of a cell or a range of
cells in MS Excel spreadsheet. The format of using Range is as follows:

Range(“cell Name”).Value=K or Range(“Range of Cells”).Value=K

Where Value is the property of Range and K can be a numeric value or a string
6
Example 1.2

Private Sub CommandButton1_Click ()

Range (“A1”).Value= “VBA”

End Sub

The above example will enter the text “VBA” into cell A1 of the MS Excel spreadsheet
when the user presses the command button. You can also use Range without the
Value property, as shown in Example 1.3:

Example 1.3

Private Sub CommandButton1_Click ()

Range ("A1") = 100

End Sub

In the above example, clicking the command button with enter the value of 100 into
cell A1 of the MS Excel spreadsheet. The follow example demonstrates how to input
values into a range of cells:

Example 1.4

Private Sub CommandButton1_Click ()

Range ("A1:A10") = 100

End Sub
7
Chapter 2

Working with Variables in Excel VBA

2.1 The Concept of Variables

Variables are like mail boxes in the post office. The contents of the variables change
every now and then, just like the mail boxes. In Excel VBA, variables are areas
allocated by the computer memory to hold data. Like the mail boxes, each variable
must be given a name. To name a variable in Excel VBA, you have to follow a set of
rules, as follows:

a) Variable Names

The following are the rules when naming the variables in VBA
 It must be less than 255 characters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted
Examples of valid and invalid variable names are displayed in Table 2.1

Table 2.1: Examples of valid and invalid variable names

Valid Name Invalid Name


My_Car My.Car
this year 1NewBoy
Long_Name_Can_beUSE He&HisFather *& is not acceptable
Group88 Student ID * Space not allowed
8
b) Declaring Variables

In VBA, we need to declare the variables before using them by assigning names and
data types. There are many VBA data types, which can be grossly divided into two
types, namely the numeric data types and the non-numeric data types.

i) Numeric Data Types

Numeric data types are types of data that consist of numbers, which can be
computed mathematically with various standard arithmetic operators such as addition,
subtraction, multiplication, division and more. In VBA, the numeric data are divided
into 7 types, which are summarized in Table 2.2.

Table 2.2: Numeric Data Types

Type Storage Range of Values


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single 4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for
negative values
Double 8 bytes
4.94065645841247E-324 to 1.79769313486232e+308 for
positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
Decimal 12 bytes
+/- 7.9228162514264337593543950335 (28 decimal places).
9
ii) Non-numeric Data Types

Nonnumeric data types are summarized in Table 2.3

Table 2.3: Nonnumeric Data Types


Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string

You can declare the variables implicitly or explicitly. For example, sum=text1.text
means that the variable sum is declared implicitly and ready to receive the input in
textbox1. Other examples of implicit declaration are volume=8 and label=”Welcome”.
On the other hand, for explicit declaration, variables are normally declared in the
general section of the code window using the Dim statements. Here is the syntax:

Dim variableName as DataType

Example 2.1

Dim password As String


Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim BirthDay As Date
10
You may also combine them into one line, separating each variable with a comma, as
follows:

Dim password As String, yourName As String, firstnum As Integer.

If the data type is not specified, VBE will automatically declare the variable as a
Variant. For string declaration, there are two possible formats, one for the variable-
length string and another for the fixed-length string. For the variable-length string, just
use the same format as Example 2.1 above. However, for the fixed-length string, you
have to use the format as shown below:

Dim VariableName as String * n

Where n defines the number of characters the string can hold. For example, Dim
yourName as String * 10 mean yourName can hold no more than 10 Characters.

Example 2.2
In this example, we declared three types of variables, namely the string, date and
currency.
Private Sub CommandButton1_Click()

Dim YourName As String, BirthDay As Date, Income As Currency

YourName = "Alex"

BirthDay = "1 April 1980"

Income = 1000

Range("A1") = YourName

Range("A2") = BirthDay

Range("A3") = Income

End Sub
11

Figure 2.1: Output screen for Example 2.2

2.2 The use of Option Explicit

The use of Option Explicit is to help us to track errors in the usage of variable names
within a program code. For example, if we commit a typo, VBE will pop up an error
message “Variable not defined”. Indeed, Option Explicit forces the programmer to
declare all the variables using the Dim keyword. It is a good practice to use Option
Explicit because it will prevent us from using incorrect variable names due to typing
errors, especially when the program gets larger. With the usage of Option Explicit, it
will save us time in debugging our programs.

When Option Explicit is included in the program code, we have to delare all variables
with the Dim keyword. Any variable not declared or wrongly typed will cause the
program to popup the “Variable not defined” error message. We have to correct the
error before the program can continue to run.
12
Example 2.3

This example uses the Option Explicit keyword and it demonstrates how a typo is
being tracked.

Option Explicit

Private Sub CommandButton1_Click()


Dim YourName As String, password As String
YourName = "John"
password = 12345
Cells(1, 2) = YourNam
Cells(1, 3) = password
End Sub

The typo is YourNam and the error message ‘variable not defined” is displayed .

Figure 2.2: Error message due to typo error


13
2.3 Assigning Values to the Variables

After declaring various variables using the Dim statements, we can assign values to
those variables. The general format of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression
could be a mathematical expression, a number, a string, a Boolean value (true or
false) and more. Here are some examples:
firstNumber=100

secondNumber=firstNumber-99

userName="John Lyan"

userpass.Text = password

Label1.Visible = True

Command1.Visible = false

ThirdNumber = Val(usernum1.Text)

total = firstNumber + secondNumber+ThirdNumber

2.4 Performing Arithmetic Operations in Excel VBA

In order to compute input from the user and to generate results in Excel VBA, we can
use various mathematical operators. In Excel VBA, except for + and -, the symbols
for the operators are different from normal mathematical operators, as shown in
Table 2.3.
14
Table 2.3: Arithmetic Operators
Operator Mathematical function Example
^ Exponential 2^4=16
* Multiplication 4*3=12
/ Division 12/4=3
Modulus (return the remainder from an
Mod 15 Mod 4=3
integer division)
\ Integer Division (discards the decimal places) 19\4=4
"Visual"&"Basic"="Visual
+ or & String concatenation
Basic"

Example 2.4
Option Explicit

Private Sub CommandButton1_Click ()

Dim number1, number2, number3 as Single

Dim total, average as Double

number1=Cells (1, 1).Value

number1=Cells (2, 1).Value

number3= Cells (3, 1).Value

Total=number1+number2+number3

Average=Total/3

Cells (5, 1) =Total

Cells (6, 1) =Average

End Sub
15
In example 2.4, three variables are declared as single and another two variables are
declared as variant. Variant means the variable can hold any numeric data type. The
program computes the total and average of the three numbers that are entered into
three cells in the Excel spreadsheet.

Example 2.5
Option Explicit

Private Sub CommandButton1_Click()

Dim secondName As String, yourName As String

firstName = Cells(1,1).Value

secondName = Cells(2,1).Value

yourName = firstName + " " + secondName

Cells(3,1) = yourName

End Sub

In the above example, three variables are declared as string. The variable firstName
and the variable secondName will receive their data entered by the user into
Cells(1,1) and cells(2,1) respectively. The variable yourName will be assigned the
data by combining the first two variables. Finally, yourName is displayed on Cells (3,
1). Performing addition on strings will result in concatenation of the strings, as shown
in figure 2.3 below. Names in A1 and A2 are joined up and displayed in A3.

Figure 2.3: Concatenation of Strings


16
Chapter 3

Using Message box and Input box

There are many built-in functions available in Excel VBA which we can use to
streamline our VBA programs. Among them, message box and input box are most
commonly used. These two functions are useful because they make the Excel VBA
macro programs more interactive. The input box allows the user to enter the data
while the message box displays output to the user.

3.1 The MsgBox ( ) Function

The objective of the MsgBox function is to produce a pop-up message box and
prompt the user to click on a command button before he or she can continue. The
code for the message box is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, displays the message in the message box. The Style
Value determines what type of command button that will appear in the message box.
Table 3.1 lists the command button that can be displayed. The Title argument
displays the title of the message box.
17
Table 3.1: Style Values and Command Buttons
Style Value Named Constant Button Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

We can use the named constant in place of integers for the second argument to
make the programs more readable. In fact, VBA will automatically show a list of
named constants where you can select one of them. For example,
yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu") and
yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu") are the
same. yourMsg is a variable that holds values that are returned by the MsgBox ( )
function. The values are determined by the type of buttons being clicked by the users.
It has to be declared as Integer data type in the procedure or in the general
declaration section. Table 3.2 shows the values, the corresponding named constants
and the buttons.
18
Table 3.2: Returned Values and Command Buttons

Value Named Constant Button Clicked


1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button

Example 3.1
In this example, the message in cell (1,2) “Your first VBA program” will be displayed
in the message box. As no named constant is added, the message will simply display
the message and the “OK” button, as shown in Figure 3.1

Private Sub CommandButton1_Click()

Dim YourMsg As String

Cells(1, 2) = "Your first VBA program"

YourMsg = Cells(1, 2)

MsgBox YourMsg

End Sub
19

Figure 3.1: Message box with the OK button

Example 3.2
In this Example, the named constant vbYesNoCancel is added as the second
argument, so the message box will display the Yes, No and the Cancel buttons, as
shown in Figure 3.2.
Private Sub CommandButton1_Click()

Dim YourMsg As String

Cells(1, 2) = "Your first VBA program"

YourMsg = Cells(1, 2)

MsgBox YourMsg, vbYesNoCancel

End Sub
20

Figure 3.2: Message box with the Yes, No and Cancel buttons

To make the message box looks more sophisticated, you can add an icon beside the
message. There are four types of icons available in VBE, as shown in Table 11.3.

Table 3.3
21
Value Named Constant Icon

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

Example 3.3

The code in this example is basically the same as Example 3.2, but the named
vbExclamation is added as the third argument. The two name constants can be
joined together using the “+” sign. The message box will now display the exclamation
icon, as shown in Figure 3.3.

Private Sub CommandButton1_Click()

Dim YourMsg As String

Cells(1, 2) = "Your first VBA program"

YourMsg = Cells(1, 2)

MsgBox YourMsg, vbYesNoCancel + vbExclamation

End Sub
22

Figure 3.3: Message box with the exclamation icon.

You can even track which button is clicked by the user based on the returned values
shown in Table 3.2. In Example 3.4, the conditional operators If….Then…Else are
used. You do not have to really understand the program logics yet, they will be
explained in later chapter.

Example 3.4
23
Private Sub CommandButton1_Click()

Dim testMsg As Integer

testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test

Message")

If testMsg = 6 Then

Cells(1,1).Value = "Yes button was clicked"

ElseIf testMsg = 7 Then

Cells(1,1).Value = "No button was clicked"

Else

Cells(1,1).Value = "Cancel button was clicked"

End If

End Sub

3.2 The InputBox( ) Function

An InputBox( ) is a function that displays an input box where the user can enter a
value or a message in the form of text. The format is
myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type but typically it is declared as a string, which


accepts the message input by the users. The arguments are explained as follows:

• Prompt - The message displayed in the inputbox.


• Title - The title of the Input Box.
• default-text - The default text that appears in the input field where users can
use it as his intended input or he may change it to another message.
• x-position and y-position - the position or the coordinates of the input box.

Example 3.5
24
The Interface of example 3.5 is shown in Figure 3.4

Private Sub CommandButton1_Click()

Dim userMsg As String

userMsg = InputBox("What is your message?", "Message Entry Form", "Enter

your messge here", 500, 700)

Cells(1,1).Value=userMsg

End Sub

When the user clicks the OK button, the input box as shown in Figure 3.4 will appear.
Notice that the caption of the input box is "Message Entry Form" and the prompt
message is “What is your message”. After the user enters the message and clicks
the OK button, the message will be displayed in cell A1

Figure 3.4: The input box


25
Chapter 4

Using If….Then….Else in Excel VBA

Visual Basic Editor (VBE) in MS Excel is just as powerful as the stand alone Visual
Basic compiler in the sense that you can use the same commands in programming.
For example, you can use If…Then...Else structure to control program flow in VBE
that execute an action based on certain conditions. To control the program flow, we
need to use the conditional operators as well as the logical operators, which are
discussed in the following sections.

4.1 Conditional Operators

To control the VBA program flow, we can use various conditional operators. Basically,
they resemble mathematical operators. Conditional operators are very powerful tools
which let the VBA program compare data values and then decide what action to take.
For example, it can decide whether to execute or terminate a program. These
operators are shown in Table 4.1.

Table 4.1: Conditional Operators


Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to
26
* You can also compare strings with the above operators. However, there are certain
rules to follows: Upper case letters are lesser than lowercase letters,
"A"<"B"<"C"<"D".......<"Z" and numbers are lesser than letters.

4.2 Logical Operators

In addition to conditional operators, there are a few logical operators that offer added
power to the VBA programs. They are shown in Table 4.2.

Table 4.2: Logical Operators


Operator Meaning
And Both sides must be true
or One side or other must be true
Xor One side or other must be true but not both
Not Negates truth

4.3 Using If.....Then.....Elseif….Else Statements with Operators

To effectively control the VBA program flow, we shall use the If...Then...Else
statement together with the conditional operators and logical operators.
The general format for If...Then...Elseif….Else statement is as follows:

If conditions Then

VB expressions
27
Elseif

VB expressions

Else

VB expressions

End If

* Any If...Then...Else statement must end with End If. Sometime it is not necessary to
use Else.

Example 4.1
Private Sub CommandButton1_Click()

Dim firstnum, secondnum As Single

firstnum = Cells(1,1).Value

secondnum = Cells(1,2).Value

If firstnum>secondnum Then

MsgBox “ The first number is greater than the second number”

If firstnum<secondnum Then

MsgBox “ The first number is less than the second number”

Else

MsgBox “ The two numbers are equal ”

End If

End Sub

In this example, the program compares the values in cells (1, 1) and cells (1, 2) and
displays the appropriate comment in a message box. For example, If the first number
28
is less than the second number, it will show the message “The first umber is less than
the second number”, as shown in Figure 4.1.

Figure 4.1

Example 4.2

In this program, you place the command button on the MS Excel spreadsheet and
go into the VBE by clicking the button. At the VBE, key in the program code as
shown below:

Private Sub CommandButton1_Click()


29
Dim mark As Integer
Dim grade As String
Randomize Timer
mark = Int(Rnd * 100)
Cells(1, 1).Value = mark
If mark < 20 And mark >= 0 Then
grade = "F"
Cells(2, 1).Value = grade
ElseIf mark < 30 And mark >= 20 Then
grade = "E"
Cells(2, 1).Value = grade
ElseIf mark < 40 And mark >= 30 Then
grade = "D"
Cells(2, 1).Value = grade
ElseIf mark < 50 And mark >= 40 Then
grade = "C-"
Cells(2, 1).Value = grade
ElseIf mark < 60 And mark >= 50 Then
grade = "C"
Cells(2, 1).Value = grade
ElseIf mark < 70 And mark >= 60 Then
grade = "C+"
Cells(2, 1).Value = grade
ElseIf mark < 80 And mark >= 70 Then
grade = "B"
Cells(2, 1).Value = grade
ElseIf mark <= 100 And mark > -80 Then
grade = "A"
Cells(2, 1).Value = grade
End If
End Sub

We use randomize timer and the Rnd function to generate random numbers. In order
to generate random integers between 0 and 100, we combined the Int and Rnd
30
functions, Int(Rnd*100). For example, when Rnd=0.6543, then Rnd*100=65.43, and
Int(65.43)=65. Using the statement cells (1,1).Value=mark will place the value of 65
into cell(1,1).

Now, based on the mark in cells(1,1), I use the If.......Then....Elseif statement to put
the corresponding grade in cells(2,1). So, when you click on command button 1, it will
generate a random number between 1 and 100 and places it in cells (1, 1) and the
corresponding grade in cells (2,1). The output is shown in Figure 4.2.

Figure 4.2

Example 4.3

This example demonstrates the use of the Not operator.


31
Private Sub CommandButton1_Click()

Dim x, y As Integer

x = Int(Rnd * 10) + 1

y = x Mod 2

If Not y = 0 Then

MsgBox " x is an odd number"

Else

MsgBox " x is an even number"

End If

End Sub

In the above example, Rnd is a randomize function that produces random number
between 0 and 1. So Rnd*10 produces a random number between 0 and 9. Int is a
function in VBA that returns an integer. Therefore, Int(Rnd*10)+1 generates random
numbers between 1 and 10. Mod is the operator that returns the remainder when a
number is divided by another number. If x is an even number, x Mod 2 will produce a
zero. Based on this logic, if x Mod 2 is not zero, it is an odd number; otherwise it is an
even number.
32
Chapter 5

For……Next Loop

Looping is a very useful feature of Excel VBA because it makes repetitive works
easier. There are two kinds of loops in VB, the For.......Next loop and the Do...Loop.
In this chapter, we will discuss the For....Next loop. The format of a For…..Next loop
is

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

We will demonstrate the usage of the For….Next loop with a few examples.

Example 5.1

Private Sub CommandButton1_Click()

Dim i As Integer

For i = 1 To 10

Cells(i, 1).Value = i

Next

End Sub

In this example, you place the command button on the spreadsheet then click on it to
go into the Visual Basic editor. When you click on the button , the VBA program will
fill cells(1,1) with the value of 1, cells(2,1) with the value of 2, cells(3,1) with the value
of 3......until cells (10,1) with the value of 10. The position of each cell in the Excel
33
spreadsheet is referenced with cells (i,j), where i represents row and j represent
column.

Figure 5.1: For….Next loop with single step increment

Example 5.2

In this example, the step increment is used. Here, the value of i increases by 2 after
each loop. Therefore, the VBA programs will fill up alternate cells after each loop.
When you click on the command button, cells (1, 1) will be filled with the value of 1,
cells (2, 1) remains empty, cells (3, 1) filled with value of 3 and etc.
34
Private Sub CommandButton1_Click()

Dim i As Integer

For i = 1 To 15 step 2

Cells(i, 1).Value = i

Next

End Sub

Figure 5.2: For….Next loop with step increment


35
If you wish to exit the For ….Next loop after a condition is fulfilled, you can use the
Exit For statement, as shown in Example 5.3.

Example 5.3
In this example, the program will stop once the value of I reaches the value of 10.

Private Sub CommandButton1_Click()


Dim i As Integer
For i = 1 To 15
Cells(i, 1).Value = i
If i >= 10 Then
Exit For
End If
Next i
End Sub

Figure 5.3: The output of Example 5.3


36
In previous examples, the For…Next loop will only fill up values through one column
or one row only. To be able to fill up a range of values across rows and columns, we
can use the nested loops, or loops inside loops. This is illustrated in Example 5.4.

Example 5.4
Private Sub CommandButton1_Click ()
Dim i, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells (i, j).Value = i + j
Next j
Next i
End Sub

In this example, when i=1, the value of j will iterate from 1 to 5 before it goes to the
next value of i, where j will iterate from I to 5 again. The loops will end when i=10 and
j=5. In the process, it sums up the corresponding values of i and j. The concept can
be illustrated in the table below:

j 1 2 3 4 5
i
1 (1, 1) (1, 2) (1, 3) (1, 4) (1, 5)
2 (2, 1) (2, 2) (2, 3) (2, 4) (2, 5)
3 (3, 1) (3, 2) (3, 3) (3, 4) (3, 5)
4 (4, 1) (4, 2) (4, 3) (4, 4) (4, 5)
5 (5, 1) (5, 2) (5, 3) (5, 4) (5, 5)
6 (6, 1) (6, 2) (6, 3) (6, 4) (6, 5)
7 (7, 1) (7, 2) (7, 3) (7, 4) (7, 5)
8 (8, 1) (8, 2) (8, 3) (8, 4) (8, 5)
9 (9, 1) (9, 2) (9, 3) (9, 4) (9, 5)
10 (10, 1) (10, 2) (10, 3) (10, 4) (10, 5)
37

Figure 5.4: The output of Example 5.4

Example 5.5

This is a simple VBA counter that can count the number of passes and the number of
failures for a list of marks obtained by the students in an examination. The program
also differentiates the passes and failures with blue and red colors respectively. Let’s
examine the code below:

Private Sub CommandButton1_Click()


38
Dim i, counter As Integer

For i = 1 To 20

If Cells(i, 2).Value > 50 Then

counter = counter + 1

Cells(i, 2).Font.ColorIndex = 5

Else

'do nothing

Cells(i, 2).Font.ColorIndex = 3

End If

Next i

Cells(21, 2).Value = counter

Cells(22, 2).Value = 20 - counter

End Sub

This program combines the For..Next and the If ...Then...Else statements to control
the program flow. If the value in that cell is more than 50, the value of counter is
increased by 1 and the font color is changed to blue (colorIndex = 5) , otherwise
there is no increment in the counter and the font color is changed to red
(ColorIndex=3). We will discuss more about the Color property in a later chapter. The
output is shown in Figure 5.5.
39

Figure 5.5: The VBA counter


40
Chapter 6

Do……Loop
In the previous chapter, you have learned how to use the For........Next loop to
execute a repetitive process. In this chapter, you will learn about another looping
method known as the Do Loop. There are four ways you can use the Do Loop as
shown below :

The formats are

a) Do While condition

Block of one or more VB statements

Loop

b) Do

Block of one or more VB statements

Loop While condition

c) Do Until condition

Block of one or more VB statements

Loop

d) Do

Block of one or more VB statements

Loop Until condition


41
Example 6.1
Private Sub CommandButton1_Click()

Dim counter As Integer

Do

counter = counter + 1

Cells(counter, 1) = counter

Loop While counter < 10

End Sub
In this example, the program will keep on adding 1 to the preceding counter value as
long as the counter value is less than 10. It displays 1 in cells (1,1), 2 in cells(2,1)…..
until 10 in cells (10,1).

Example 6.2
Private Sub CommandButton1_Click()

Dim counter As Integer

Do Until counter = 10

counter = counter + 1

Cells(counter, 1) = 11 - counter

Loop

End Sub
42
Example 6.3

Private Sub CommandButton1_Click ()

Dim counter As Integer

Do Until counter = 10

counter = counter + 1

Cells(counter, 1) = 11 - counter

Loop

End Sub

In this example, the program will keep on adding 1 to the preceding counter value
until the counter value reaches 10. It displays 10 in cells (1, 1), 9 in cells (2, 1)…..
until 1 in cells (10,1).

Examle 6.3

Private Sub CommandButton1_Click()

Dim counter , sum As Integer

'To set the alignment to center

Range("A1:C11").Select

With Selection

.HorizontalAlignment = xlCenter

End With

Cells(1, 1) = "X"

Cells(1, 2) = "Y"
43
Cells(1, 3) = "X+Y"

Do While counter < 10

counter = counter + 1

Cells(counter + 1, 1) = counter

Cells(counter + 1, 2) = counter * 2

sum = Cells(counter + 1, 1) + Cells(counter + 1, 2)

Cells(counter + 1, 3) = sum

Loop

End Sub

The above program will display the values of X in cells(1,1) to cells(11,1). The values
of Y are X2 and the values are displayed in column 2, i.e. from cells(2,1) to cells(2,11).
Finally, it shows the values of X+Y in column 3, i.e. from cells(3,1) to cells(3,11)
44
Chapter 7
Select Case.........End Select

Normally it is sufficient to use the conditional statement If....Then....Else for multiple


options or selections programs. However, if there are too many different cases, the
If...Then...Else structure could become too bulky and difficult to debug if problems
arise. Fortunately, Visual Basic provides another way to handle complex multiple
choice cases, that is, the Select Case.....End Select decision structure. The general
format of a Select Case...End Select structure is as follow:

Select Case variable

Case value 1

Statement

Case value 2

Statement

Case value 3

Statement

Case Else

End Select

In the following example, the program will process the grades of students according
to the marks given.
45
Example 7.1

Private Sub CommandButton1_Click()


Dim mark As Single
Dim grade As String
mark = Cells(1, 1).Value
'To set the alignment to center
Range("A1:B1").Select
With Selection
.HorizontalAlignment = xlCenter
End With
Select Case mark
Case 0 To 20
grade = "F"
Cells(1, 2) = grade
Case 20 To 29
grade = "E"
Cells(1, 2) = grade
Case 30 To 39
grade = "D"
Cells(1, 2) = grade
Case 40 To 59
grade = "C"
Cells(1, 2) = grade
Case 60 To 79
grade = "B"
Cells(1, 2) = grade
Case 80 To 100
grade = "A"
Cells(1, 2) = grade
Case Else
grade = "Error!"
Cells(1, 2) = grade
End Select
End Sub
46
Chapter 8
Excel VBA Objects Part 1–An Introduction
8.1: Objects

Most programming languages today deal with objects, a concept called object
oriented programming. Although Excel VBA is not a truly object oriented
programming language, it does deal with objects. VBA object is something like a tool
or a thing that has certain functions and properties, and can contain data. For
example, an Excel Worksheet is an object, a cell in a worksheet is an object, a range
of cells is an object, the font of a cell is an object, a command button is an object, and
a text box is an object and more.

In order to view the VBA objects, you can insert a number of objects or controls into
the worksheet, and click the command button to go into the code window. The upper
left pane of the code window contains the list of objects you have inserted into the
worksheet; you can view them in the dropdown dialog when you click the down arrow.
The right pane represents the events associated with the objects.

Figure 8.1: Some common Excel VBA objects.


47
To view all the available objects, you can click on the objects browser in the code
window.

Figure 8.2: Objects browser that lists the entire Excel VBA objects.
48
8.2: Properties and Methods

8.2.1 Properties

An Excel VBA object has properties and methods. Properties are like the
characteristics or attributes of an object. For example, Range is an Excel VBA object
and one of its properties is value. We connect an object to its property by a period (a
dot or full stop). The following example shows how we connect the property value to
the Range object.

Example 8.1

Private Sub CommandButton1_Click()

Range("A1:A6").Value = 10

End Sub

In this example, by using the value property, we can fill cells A1 to A6 with the value
of 10. However, because value is the default property, it can be omitted. So the
above procedure can be rewritten as

Example 8.2

Private Sub CommandButton1_Click()

Range("A1:A6")= 10

End Sub

Cell is also an Excel VBA object, but it is also the property of the range object. So an
object can also be a property, it depends on the hierarchy of the objects. Range has
higher hierarchy than cells, and interior has lower hierarchy than Cells, and color has
lower hierarchy than Interior, so you can write
49
Range("A1:A3").Cells(1, 1).Interior.Color = vbYellow

This statement will fill cells (1, 1) with yellow color. Notice that although the Range
object specifies a range from A1 to A3, but the cells property specifies only cells(1,1)
to be filled with yellow color, it sort of overwrites the range specified by the Range
object.

Font is an object which belongs to the Range object. Font has its own properties. For
example, Range(“A1:A4”).Font.Color=vbYellow , the color property of the object Font
will fills all the contents from cell A1 to cell A4 with yellow color.

Sometime it is not necessary to type the properties, Excel VBA IntelliSense will
display a drop-down list of proposed properties after you type a period at the end of
the object name. You can then select the property you want by double clicking it or by
highlighting it then press the Enter key. The IntelliSense drop-down is shown in
Figure 8.3.

Figure 8.3: The IntelliSense Drop-Down List


50
Count is also a property of the Range object. It shows the number of cells in the
specified range. For example, Range (“A1:A10”).Count will return a value of 10. In
order to display the number of cells returned, you can write the following code.

Example 8.3

Private Sub CommandButton1_Click()

Dim tcount As Integer

tcount = Range("A1:A6").count

Range("A10") = tcount

End Sub

8.2.2 Methods

Besides having properties, Excel VBA objects also have methods. Methods normally
do something or perform certain operations. For example, ClearContents is a method
of the range object. It clears the contents of a cell or a range of cells. You can write
the following code to clear the contents:

Example 8.4

Private Sub CommandButton1_Click()

Range(“A1:A6”).ClearContents

End Sub

You can also let the user select his own range of cells and clear the contents by
using the InputBox function, as shown in Example 8.5
51
Example 8.5

Private Sub CommandButton1_Click()

Dim, selectedRng As String

selectedRng = InputBox("Enter your range")

Range(selectedRng).ClearContents

End Sub

In order to clear the contents of the entire worksheet, you can use the following code:

Sheet1.Cells.ClearContents

However, if you only want to clear the formats of an entire worksheet, you can use
the following syntax:

Sheet1.Cells.ClearFormats

To select a range of cells, you can use the Select method. This method selects a
range of cells specified by the Range object. The syntax is

Range(“A1:A5”).Select

Example 8.6: The code to select a range of cells

Private Sub CommandButton1_Click()

Range("A1:A5").Select

End Sub
52
Example 8.7

This example allows the user to specify the range of cells to be selected.

Private Sub CommandButton1_Click()

Dim selectedRng As String

selectedRng = InputBox("Enter your range")

Range(selectedRng).Select

End Sub

To deselect the selected range, we can use the Clear method.

Range(“CiRj:CmRn”).Clear

Example 8.8

In this example, we insert two command buttons, the first one is to select the range
and the second one is to deselect the selected range.

Private Sub CommandButton1_Click()

Range("A1:A5").Select

End Sub

Private Sub CommandButton2_Click()

Range("A1:A5").Clear

End Sub
53
Instead of using the Clear method, you can also use the ClearContents method.

Another very useful method is the Autofill method. This method performs an autofill
on the cells in the specified range with a series of items including numbers, days of
week, months of year and more. The format is

Expression.AutoFill (Destination, Type)

Where Expression can be an object or a variable that returns and object. Destination
means the required Range object of the cells to be filled. The destination must
include the source range. Type means type of series, such as days of week, months
of year and more. The AutoFill type constant is something like xlFillWeekdays,
XlFillDays, XlFillMonths and more.

Example 8.9:

Private Sub CommandButton1_Click()

Range(“A1”)=1

Range(“A2”)=2

Range("A1:A2").AutoFill Destination:=Range("A1:A10")

End Sub

In this example, the source range is A1 to A2. When the user clicks on the command
button, the program will first fill cell A1 with 1 and cell A2 will 2, and then
automatically fills the Range A1 to A10 with a series of numbers from 1 to 10.
54
Example 8.10

Private Sub CommandButton1_Click()

Cells(1, 1).Value = "Monday"

Cells(2, 1).Value = "Tuesday"

Range("A1:A2").AutoFill Destination:=Range("A1:A10"), Type:=xlFillDays

End Sub

In this example, when the user clicks on the command button, the program will first fill
cell A1 with “Monday” and cell A2 wilh “Tuesday”, and then automatically fills the
Range A1 to A10 with the days of a week.

Example 8.11

This example allows the user to select the range of cells to be automatically filled
using the Autofill method. This can be achieved with the use of the InputBox. Since
each time we want to autofill a new range, we need to clear the contents of the entire
worksheet using the Sheet1.Cells.ClearContents statement.

Private Sub CommandButton1_Click()

Dim selectedRng As String

Sheet1.Cells.ClearContents

selectedRng = InputBox("Enter your range")

Range("A1") = 1

Range("A2") = 2

Range("A1:A2").AutoFill

Destination:=Range(selectedRng)

End Sub
55

Chapter 9
Excel VBA Objects Part 2 –The Workbook Object
In the previous chapter, we have learned about Excel VBA objects and their
properties and methods. In this chapter, we shall learn specifically about the
Workbook object as it is one of the most important Excel VBA objects. It is also at the
top of the hierarchy of the Excel VBA objects. We will deal with properties and
methods associated the Workbook object.

9.1 The Workbook Properties.

When we write VBA code involving the Workbook object, we use Workbooks. The
reason is that we are dealing with a collection of workbooks most of the time, so
using Workbooks enables us to manipulate multiple workbooks at the same time.

When will deal with multiple workbooks, we can use indices to denote different
workbooks that are open, using the syntax Workbooks (i), where i is an index. For
example, Workbooks (1) denotes Workbook1, Workbooks (2) denotes Workbook2
and more.

A workbook has a number of properties. Some of the common properties are Name,
Path and FullName Let’s look at the following example:

Example 9.1

Private Sub CommandButton1_Click()

MsgBox Workbooks(1).Name

End Sub
56
The program will cause a message dialog box to pop up and displays the first
workbook name, i.e. workbook_object1.xls as shown in Figure 9.1 below:

Figure 9.1: The name of the Excel workbook

If we have only one open workbook, we can also use the syntax ThisWorkbook in
place of Workbook (1), as follows:

Private Sub CommandButton1_Click ()

MsgBox ThisWorkbook.Name

End Sub

Example 9.2

Private Sub CommandButton1_Click ()

MsgBox ThisWorkbook.Path

End Sub
Or you can use the following code
Private Sub CommandButton1Click ()

MsgBox Workbooks ("workbook_object1.xls").Path

End Sub

The output is shown below:


57

Figure 9.2: The path of the opened workbook

Example 9.3

This example will display the path and name of the opened workbook. The code is:

Private Sub CommandButton1_Click ()

MsgBox ThisWorkbook.FullName

End Sub

Or

Private Sub CommandButton1Click()

MsgBox Workbooks("workbook_object1.xls").Fullname

End Sub

The output is shown in Figure 9.3.

Figure 9.3
58
9.2 The Workbook Methods

There are a number of methods associated with the workbook object. These methods
are Save, SaveAs, Open, Close and more.

Example 9.4

In this example, when the user clicks on the command button, it will open up a dialog
box and ask the user to specify a path and type in the file name, and then click the
save button, not unlike the standard windows SaveAs dialog, as shown in Figure 9.5.

Private Sub CommandButton1_Click()


fName = Application.GetSaveAsFilename
ThisWorkbook.SaveAs Filename:=fName
End Sub

Figure 9.4: The SaveAs dialog


59
Another method associated with the workbook object is open. The syntax is

Workbooks.Open ("File Name")

Example 9.5

In this example, when the user click on the command button, it wil open the file
workbook_object1.xls under the path C:\Users\liewvk\Documents\

Private Sub CommandButton1_Click()

Workbooks.Open ("C:\Users\liewvk\Documents\workbook_object1.xls")

End Sub

The close method is the command that closes a workbook. The syntax is

Workbooks (i).Close

Example 9.6

In this example, when the user clicks the command button, it will close Workbooks (1).

Private Sub CommandButton1_Click()

Workbooks (1).Close

End Sub
60
Chapter 10
Excel VBA Objects Part 3 –The Worksheet Object

10.1 The Worksheet Properties

Similar to the Workbook Object, the Worksheet has its own set of properties and
methods. When we write VBA code involving the Worksheet object, we use
Worksheets. The reason is that we are dealing with a collection of worksheets most
of the time, so using Worksheets enables us to manipulate multiple worksheets at the
same time.

Some of the common properties of the worksheet are name, count, cells, columns,
rows and columnWidth.

Example 10.1

Private Sub CommandButton1_Click()

MsgBox Worksheets(1).Name

End Sub

The above example will cause a pop-up dialog that displays the worksheet name as
sheet 1, as shown below:

Figure 10.1
61
The count property returns the number of worksheets in an opened workbook.

Example 10.2

Private Sub CommandButton1_Click()

MsgBox Worksheets.Count

End Sub

The output is shown in Figure 10.2.

Figure 10.2

Example 10.3

The count property in this example will return the number of columns in the
worksheet.

Private Sub CommandButton1_Click()

MsgBox Worksheets(1).Columns.Count

End Sub

* It is suffice to write MsgBox Columns.Count as the worksheet is considered the


active worksheet. The output is shown below:
62

Figure 10.3

Example 10.4

The count property in this example will return the number of rows in the worksheet.

Private Sub CommandButton1_Click()

MsgBox Worksheets(1).Rows.Count

End Sub

Figure 10.4

10.2 The Worksheet Methods

Some of the worksheet methods are add, delete, select, SaveAs, copy, paste and
more.
63
Example 10.5

In this example, when the user clicks the first command button, it will add a new
sheet to the workbook. When the user clicks the second command button, it will
delete the new worksheet that has been added earlier.

Private Sub CommandButton1_Click()

Worksheets. Add

End Sub

Private Sub CommandButton2_Click()

Worksheets(1).Delete

End Sub

Example 10.6

The select method associated with worksheet let the user select a particular
worksheet. In this example, worksheet 2 will be selected.

Private Sub CommandButton1_Click()

‘Worksheet 2 will be selected

Worksheets(2).Select

End Sub

The select method can also be used together with the Worksheet’s properties Cells,
Columns and Rows as shown in the following examples.

Example 10.5
64
Private Sub CommandButton1_Click()

‘Cell A1 will be selected

Worksheets (1).Cells (1).Select

End Sub

Example 10.6

Private Sub CommandButton1_Click()

‘Column 1 will be selected

Worksheets (1).Columns (1).Select

End Sub

Example 10.7

Private Sub CommandButton1_Click()

‘Row 1 will be selected

Worksheets (1).Rows (1).Select

End Sub

Excel VBA also allows us to write code for copy and paste. Let’s look at the following
Example:

Example 10.8
65
Private Sub CommandButton1_Click()

‘To copy the content of a cell 1

Worksheets(1).Cells(1).Select

Selection.Copy

End Sub

Private Sub CommandButton2_Click()

‘To paste the content of cell 1 to cell 2

Worksheets(1).Cells(2).Select

ActiveSheet.Paste

End Sub
66
Chapter 11
Excel VBA Objects Part 4–The Range Object

11.1 The Range Properties

As an Excel VBA object, the range object is ranked lower than the worksheet object
in the hierarchy. We can also say that worksheet is the parent object of the range
object. Therefore, the Range object also inherits the properties of the worksheet
object. Some of the common properties of the range object are Columns, Rows,
Value and Formula

11.1.1 Formatting Font

There are many Range properties that we can use to format the font in Excel. Some
of the common ones are Bold, Italic, Underline, Size, Name, FontStyle, ColorIndex
and Color. These properties are used together with the Font property.

The Bold, Italic, Underline and FontStyle properties are used to format the font style.
The syntax for using Bold, Italic and Underline are similar, as shown below:

Range (“YourRange”).Font.Bold=True

Range (“YourRange”).Font.Italic=True

Range (“YourRange”).Font.Underline=True

The FontStyle property can actually be used to replace all the properties above to
achieve the same formatting effects. The syntax is as follows:

Range (“YourRange”).Font.FontStyle=”Bold Italic Underline”


67
The Name property is used to format the type of font you wish to display in the
designated range. The syntax is as follows:

Range ("A1:A3").Font. Name = "Time News Roman"

The formatting code is illustrated in Example 11.1.

Example 11.1

Private Sub CommandButton1_Click()

Range("A1:A3").Font.Bold = True

Range("A1:A3").Font.Italic = True

Range("A1:A3").Font.Underline = True

Range("A1:A3").Font.Size = 20

Range("A1:A3").Font.FontStyle = "Bold Italic Underline"

Range("A1:A3").Font.Name = "Time News Roman"

End Sub

The Font and ColorIndex properties are used together to format the font color. You
can also use the color property to display the font color,
68
Example 11.2

Private Sub CommandButton2_Click()

Range("A4:B10").Font.ColorIndex = 4

End Sub

.In this example, the font color will be displayed in green (Corresponding with

ColorIndex =4):

Range("A4:B10").Font.Color = VbRed

Example 11.2

Private Sub CommandButton1_Click()

Range("A1:B3").Columns(3).Formula = "=A1+B1"

End Sub

In this example, the formula A1+B1 will be copied down column 3 (column C) from
cell C1 to cell C3. The program automatically sums up the corresponding values
down column A and column B and displays the results in column C, as shown in
Figure 11.1.

Figure 11.1
69
The above example can also be rewritten and produces the same result as below:

Range("A1:B3").Columns(3).Formula = "=Sum(A1:B1)"

There are many formulas in Excel VBA which we can use to simplify and speed up
complex calculations. The formulas are categorized into Financial, Mathematical,
Statistical, Date ,Time and others. For example, in the statistical category, we have
Average (Mean), Mode and Median

Example 11.3

In this example, the program computes the average of the corresponding values in
column A and column B and displays the results in column C. For example, the mean
of values in cell A1 and Cell B1 is computed and displayed in Cell C1. Subsequent
means are automatically copied down Column C until cell C3.

Private Sub CommandButton1_Click()

Range("A1:B3").Columns(3).Formula = "=Average(A1:B1)”

End Sub

Example 11.4: Mode

In this example, the program computes the mode for every row in the range A1:E4
and displays them in column F. It also makes the font bold and red in color, as shown
in Figure 11.2.

Private Sub CommandButton1_Click()

Range("A1:E4").Columns(6).Formula = "=Mode(A1:E1)”

Range("A1:E4").Columns(6).Font.Bold = True

Range("A1:E4").Columns(6).Font.ColorIndex = 3

End Sub
70

Figure 11.2: Mode for each row displayed in column F

Example 11.5: Median

In this example, the program computes the median for every row in the range A1:E4
and displays them in column F. It also makes the font bold and red in color, as shown
in Figure 11.3.

Private Sub CommandButton1_Click()

Range("A1:E4").Columns(6).Formula = "=Median(A1:E1)”

Range("A1:E4").Columns(6).Font.Bold = True

Range("A1:E4").Columns(6).Font.ColorIndex = 3

End Sub
71

Figure 11.3: Median for each row displayed in column F

Example 11.6

In this example, the Interior and the Color properties will fill the cells in the range
A1:A3 with yellow color.

Private Sub CommandButton1_Click()

Range("A1:A3").Interior.Color = vbYellow

End Sub

11.2 The Range Methods

The range methods allow the range object to perform many types of operations.
They enable automation and perform customized calculations that greatly speed up
otherwise time consuming work if carried out manually.

There are many range methods which we can use to automate our works. Some of
the methods are Autofill, Clear, ClearContents, Copy, cut, PasteSpecial, and Select.
72
11.2.1 Autofill Method

This program allows the cells in range A1 to A20 to be filled automatically following
the sequence specified in the range A1 to A2. The Destination keyword is being used
here.

Example 11.7

Private Sub CommandButton1_Click ()

Set myRange = Range ("A1:A2")

Set targetRange = Range ("A1:A20")

myRange.AutoFill Destination: =targetRange

End Sub

11.2.2 Select, Copy and Paste Methods

We use the Select method to select a specified range, copy the values from that
range and then paste them in another range, as shown in the following example:

Example 11.9

Private Sub CommandButton1_Click ()

Range ("C1:C2").Select

Selection.Copy

Range ("D1:D2").Select

ActiveSheet.Paste

End Sub

*We can also use the Cut method in place of Copy in the above example.
73
11.2.2 Copy and PasteSpecial Methods

The Copy and the PasteSpecial methods are performed together. The copy method
will copy the contents in a specified range and the PasteSpecial method will paste
the contents into another range. However, unlike the paste method, which just pastes
the values into the target cells, the PasteSpecial method has a few options. The
options are PasteValues, PasteFormulas, PasteFormats or PasteAll. The
PasteValues method will just paste the values of the original cells into the targeted
cells while the PasteFormulas will copy the formulas and update the values in the
targeted cells accordingly.

Example 11.10

Private Sub CommandButton1_Click()

Range("C1:C2").Copy

Range("D1:D2").PasteSpecial Paste:=xlPasteValues

Range("E1:E2").PasteSpecial Paste:=xlPasteFormulas

Range("F1:F2").PasteSpecial Paste:=xlPasteFormats

Range("G1:G2").PasteSpecial Paste:=xlPasteAll

End Sub

The output is displayed in Figure 11.4. The original values are pasted to the range
D1:D2 while the formula is updated in the range E1:E2 but not the formats. The
original formats for the font are bold and red. The formats are reflected in range
F1:F2 but the formulas were not pasted there. Lastly, everything is copied over to the
range G1:G2.
74

Figure 11.4

We can also modify the code above and paste them according to the Paste Values
option and the Paste Formulas option, as shown in Example 11.10.

Example 11.11

Private Sub CommandButton1_Click()

Range("C1:C2").Select

Selection.Copy

Range("D1:D2").PasteSpecial Paste:=xlPasteValues

Range("E1:E2").PasteSpecial Paste:=xlPasteFormulas

End Sub
75
Chapter 12
Working with Excel VBA Controls

Excel VBE provides a number of controls that can be used to perform certain tasks
by writing VBA code for them. These controls are also known as Active-X controls.
As these controls are Excel VBA objects, they have their own properties, methods
and events. They can be found on the Excel Control Toolbox, as shown in the
diagram below:

Option Button
Spin Button
Text Box Combo Box
Label

List Box Toggle Button


Check Box Command Image
Button Scroll Bar

Figure 12.1: Excel VBA Controls

12.1 Check Box

The Check box is a very useful control in Excel VBA. It allows the user to select one
or more items by checking the checkbox or checkboxes concerned. For example, you
may create a shopping cart where the user can click on checkboxes that correspond
to the items they intend to buy, and the total payment can be computed at the same
time.

One of most important properties of the check box is Value. If the checkbox is
selected or checked, the value is true, whilst if it is not selected or unchecked, the
Value is False.
76
The usage of check box is illustrated in Example 12.1

Example 12.1

In this example, the user can choose to display the sale volume of one type of fruits
sold or total sale volume. The code is shown in next page.

Private Sub CommandButton1_Click()

If CheckBox1.Value = True And CheckBox2.Value = False

Then

MsgBox "Quantity of apple sold is” & Cells (2, 2).Value

ElseIf CheckBox2.Value = True And CheckBox1.Value = False

Then

MsgBox "Quantity of orange sold is " & Cells(2, 3).Value

Else

MsgBox "Quantity of Fruits sold is” & Cells (2, 4).Value

End If

End Sub
77

Figure 12.2: Check Boxex

12.2 Text Box

The Text Box is the standard Excel VBA control for accepting input from the user as
well as to display the output. It can handle string (text) and numeric data but not
images.

Example 12.2
In this example, we inserted two text boxes and display the sum of numbers entered
into the two textboxes in a message box. The Val function is used to convert string
into numeric values because the textbox treats the number entered as a string.
78
Private Sub CommandButton1_Click ()

Dim x As Variant, y As Variant, z As Variant

x = TextBox1.Text

y = TextBox2.Text

z = Val(x) + Val(y)

MsgBox "The Sum of " & x & " and " & y & " is " & z

End Sub

Figure 12.3: Text Boxes


79
12.3 Option Button

The option button control also lets the user selects one of the choices. However, two
or more option buttons must work together because as one of the option buttons is
selected, the other option button will be deselected. In fact, only one option button
can be selected at one time. When an option button is selected, its value is set to
“True” and when it is deselected; its value is set to “False”.

Example 12.3
This example demonstrates the usage of the option buttons. In this example, the
Message box will display the option button selected by the user. The output interface
is shown in Figure 12.4.
Private Sub OptionButton1_Click ()

MsgBox "Option 1 is selected"

End Sub

Private Sub OptionButton2_Click()

MsgBox "Option 2 is selected"

End Sub

Private Sub OptionButton3_Click()

MsgBox "Option 3 is selected"

End Sub
80

Figure 12.4: The Option Buttons

Example 12.4

In this example, If …Then….Elseif statements are used to control the action when
an option button is being selected, i.e., changing the background color of the
selected range.
Private Sub CommandButton1_Click()

If OptionButton1.Value = True Then

Range("A1:B10").Interior.Color = vbRed

ElseIf OptionButton2.Value = True Then

Range("A1:B10").Interior.Color = vbGreen

ElseIf OptionButton3.Value = True Then

Range("A1:B10").Interior.Color = vbBlue

End If

End Sub
81

Figure 12.5: Using Option Buttons

Example 12.5
In this example, the program will change the font color of the item selected.
Private Sub OptionButton1_Click()

Dim i As Integer

For i = 1 To 12

If Cells(i, 2) = "apple" Then

Cells(i, 2).Font.Color = vbGreen

End If

Next
82
End Sub

Private Sub OptionButton2_Click()

For i = 1 To 12

If Cells(i, 2) = "orange" Then

Cells(i, 2).Font.Color = vbRed

End If

Next

End Sub

Figure 12.6: Changing font color

12.4 List Box

The function of the List Box is to present a list of items where the user can click and
select the items from the list. To add items to the list, we can use the AddItem
method.
83
To clear all the items in the List Box, you can use the Clear method. The usage of
Additem method and the Clear method is shown Example 12.6.

Example 12.6
Private Sub CommandButton1_Click()
For x = 1 To 10
ListBox1.AddItem "Apple"
Next
End Sub
Private Sub CommandButton2_Click()
For x = 1 To 10
ListBox1.Clear
Next
End Sub

Figure 12.7
84
12.5 Combo Box

The function of the Combo Box is also to present a list of items where the user can
click and select the items from the list. However, the user needs to click on the small
arrowhead on the right of the combo box to see the items which are presented in a
drop-down list. In order to add items to the list, you can also use the AddItem method.

Example 12.7
Private Sub CommandButton1_Click()

ComboBox1.Text = "Apple"

For x = 1 To 10

ComboBox1.AddItem "Apple"

Next

End Sub

Private Sub CommandButton2_Click()

ComboBox1.Clear

End Sub
85

Figure 12.8

12.6 Toggle Button

Toggle button lets the user switches from one action to another alternatively. When
the Toggle button is being depressed, the value is true and when it is not depressed,
the value is false. By using the If and Else code structure, we can thus switch from
one action to another by pressing the toggle button repeatedly.
Example 12.8
In this example, the user can toggle between apple and orange as well as font colors.
Private Sub ToggleButton1_Click ()
If ToggleButton1.Value = True Then
Cells (1, 1) = "Apple"
Cells (1, 1).Font.Color = vbRed
Else
Cells (1, 1) = "Orange"
Cells (1, 1).Font.Color = vbBlue
End If
End Sub
86
Chapter 13
VBA Procedures Part 1-Functions

13.1 The Concept of Functions

A VBA procedure is a block of code that performs certain tasks. We have actually
learned about VBA procedures in our previous chapters, but all of them are event
procedures. Event procedures are VBA programs that are associated with VBA
objects such as command buttons, checkboxes, and radio buttons. However, we can
also create procedures that are independent from the event procedures. They are
normally called into the event procedures to perform certain tasks. There are two
types of the aforementioned procedures, namely Functions and Sub Procedures. In
this chapter, we will discuss functions. We will deal with Sub Procedures in the next
chapter.

13.2 Types of Functions

There are two types of Excel VBA functions; the built-in functions and the user-
defined functions. We can use built-in functions in Excel for automatic calculations.
Some of the Excel VBA built-in functions are Sum, Average, Min (to find the minimum
value in a range), Max (To find the maximum value in a range), Mode, Median and
more. However, built-in functions can only perform some basic calculations, for more
complex calculations, user-defined functions are often required. User-defined
functions are procedures created independently from the event procedures. A
Function can receive arguments passed to it from the event procedure and then
return a value in the function name. It is usually used to perform certain calculations.
87
13.3 Writing Function Code
VBA Function begins with a Function statement and ends with an End Function
statement. The program structure of a Function is as follows:
Function FunctionName (arguments) As DataType

Statements

End Function
In Excel VBA, when you type the Function statement, the End Function statement will
automatically appear.

Example 13.1
In this example, we create a function to calculate the area of a rectangle. It comprises
two arguments, one of them is to accept the value of width and the other is to accept
the value of height. Note that the function Area_Rect is called from the event
procedure (clicking the command button) and the values to be passed to the
arguments are enclosed in the parentheses.

Private Sub CommandButton1_Click()

Dim a As Variant, b As Variant

a = InputBox("Enter Width of Rectangle")

b = InputBox("Enter Height of Rectangle")

MsgBox "The area of the rectangle is” & Area_Rect(a, b)

End Sub

Function Area_Rect(x As Variant, y As Variant) As Variant

Area_Rect = x * y

End Function
88
We can also create a user-defined function to be used just as the built-in functions by
inserting a module in the Visual Basic Editor and enter the function code there. After
creating the function, we can then return to the spreadsheet and use this function as
any other built-in functions. To insert the module, click on Tool in the menu bar,
select Macro and the click on Visual Basic Editor.

Figure 13.1: Inserting Visual Basic Editor


In the Visual Basic Editor window, insert a module by clicking Insert on the menu bar,
and then click on Module.

Figure 13.2: Inserting Module

In the module environment, key in the function code for the function Area_Rect , as
shown in the diagram below.
89

Figure 13.3: Key in the VBA code for the function.

Now, you can return to the Excel spreadsheet and enter the function in any cell. In
this Example, the function is entered in cell C1 and the values of width and height are
entered in cell A1 and cell B1 respectively. Notice that the value of area is
automatically calculated and displayed in cell C1.

Figure 13.4
The formula can be copied and updated to other cells by using the autofill method, i.e.
by dragging the place holder on the bottom right corner of the cell, as shown in
Figure 13.5 below.
90

Figure 13.5: using autofill method to update the formula.

The user-defined function not only calculates numerical values, it can also return a
string, as shown in Example 13.2 below:

Example 13.2
This program computes the grades of an examination based on the marks obtained.
It employed the Select Case…….End Select code structure. The code is shown on
next page.
91

Function grade(mark As Single) As String

Select Case mark

Case 0 To 20

grade = "F"

Case 20 To 29

grade = "E"

Case 30 To 39

grade = "D"

Case 40 To 59

grade = "C"

Case 60 To 79

grade = "B"

Case 80 To 100

grade = "A"

Case Else

grade = "Error!"

End Select

End Function
In the Excel spreadsheet environment, key in the marks in column A and key in the
grade function in column B. Notice that the grades will be automatically updated in
column B as marks are entered or updated in column A, as shown in Figure 13.6
92

Figure 13.6: The grade function

Example 13.3
In this example, we create a function that calculates commissions payment based on
the commissions payment table below. We can use the If….Then…Elseif program
structure to write the function code.

Commissions Payment Table


Sales Volume($) Commissions
<500 3%
<1000 6%
<2000 9%
<5000 12%
>5000 15
93
Function Comm(Sales_V As Variant) as Variant
If Sales_V <500 Then
Comm=Sales_V*0.03
Elseif Sales_V>=500 and Sales_V<1000 Then
Comm=Sales_V*0.06
Elseif Sales_V>=1000 and Sales_V<2000 Then
Comm=Sales_V*0.09
Elseif Sales_V>=200 and Sales_V<5000 Then
Comm=Sales_V*0.12
Elseif Sales_V>=5000 Then
Comm=Sales_V*0.15
End If
End Function

After creating the Comm Function, we can then enter the sales volume in one column
and enter the formula based on the function Comm in another column. The
commissions will be automatically computed and updated accordingly.

Figure 13.7
94
13.4 Passing variables by reference and by Value in a Function

Variables in a function can be passed by reference or by value, using the keywords


ByRef and ByVal respectively. The main difference between ByRef and ByVal is
ByRef will change the value of the variable while ByVal will retain the original value of
the variable. By default, the function uses ByRef to pass variables.

Example 13.4

Private Sub CommandButton1_Click()

Dim N As Variant

N = 27

Range("A1") = CRoot(N)

Range("A2") = N

Range("A3") = CRoot2(N)

Range("A4") = N

End Sub

Function CRoot(ByRef r As Variant)

r = r ^ (1 / 3)

CRoot = r

End Function

Function CRoot2(ByVal w As Variant)

w = w ^ (1 / 3)

CRoot2 = w

End Function
95
In this example, we created two similar functions, CRoot and CRoots respectively.
However, the first function uses the ByRef keyword and the second function uses the
ByVal keyword. Notice that the value of N has changed to 3 by the function CRoot,
as shown in cell B3. Now the function CRoot2 compute the cubic root of N based on
the new value of N, i.e. 3, and shows result in cell B4. However, it does not change
the value of N, it remains as 3, as shown in cell B5.
96
Chapter 14
VBA Procedures Part 2-Sub Procedures
A sub procedure is a procedure that performs a specific task and to return values, but
it does not return a value associated with its name. However, it can return a value
through a variable name. Sub procedures are usually used to accept input from the
user, display information, print information, manipulate properties or perform some
other tasks. It is a program code by itself and it is not an event procedure because it
is not associated with a runtime procedure or a VBA control such as a command
button. It is called by the main program whenever it is required to perform a certain
task. Sub procedures help to make programs smaller and easier to manage.

A Sub procedure begins with a Sub statement and ends with an End Sub statement.
The program structure of a sub procedure is as follows:

Sub ProcedureName (arguments)

Statements

End Sub
Example 14.1

In this example, a sub procedure ResizeFont is created to resize the font in the range
if it fulfills a value greater than 40. There are two parameters or arguments
associated with the sub procedure, namely x for font size and Rge for range. This
sub procedure is called by the event procedure Sub CommandButton1_Click () and
passed the values 15 to x (for font size) and Range (“A1:A10”) to Rge (for range) to
perform the task of resizing the font to 15 for values>40 in range A1 to A10.

Private Sub CommandButton1_Click()


97
ResizeFont 15, Range("A1:A10")

End Sub

Sub ResizeFont(x As Variant, Rge As Range)

Dim cel As Range

For Each cel In Rge

If cel.Value > 40 Then

cel.Font.Size = x

End If

Next cel

End Sub

Figure 14.1: Output for Example 14.1


To make the program more flexible and interactive, we can modify the above
program to accept input from the user. The values input by the user through the input
98
boxes will be passed on to the procedure to execute the job, as shown in Example
14.2.

Example 14.2

Private Sub CommandButton1_Click()

Dim rng As String

rng = InputBox("Input range")

x = InputBox("Input Font Size")

ResizeFont x, Range(rng)

End Sub

Sub ResizeFont(x As Variant, Rge As Range)

Dim cel As Range

For Each cel In Rge

If cel.Value > 40 Then

cel.Font.Size = x

End If

Next cel

End Sub
99
Chapter 15
String Handling Functions
Excel VBA handles strings similar to the stand-alone Visual Basic program. All the
string handling functions in Visual Basic such as Left, Right, Instr, Mid and Len can
be used in Excel VBA. Some of the string handling functions are listed and explained
below:

15.1 InStr
InStr is a function that looks for the position of a substring in a phrase.
InStr (phrase,"ual") will find the substring "ual" from "Visual Basic" and then return its
position; in this case, it is fourth from the left.

15.2. Left
Left is a function that extracts characters from a phrase, starting from the left. Left
(phrase, 4) means four characters are extracted from the phrase, starting from the
leftmost position.

15.3. Right
Right is a function that extracts characters from a phrase, starting from the Right.
Right (phrase, 5) means 5 characters are extracted from the phrase, starting from the
rightmost position.

15.4. Mid
Mid is a function that extracts a substring from a phrase, starting from the position
specified by the second parameter in the bracket. Mid (phrase, 8, 3) means a
substring of three characters are extracted from the phrase, starting from the 8th
position from the left.
100
15.5. Len
Len is a function that returns the length of a phrase.

Example 15.1
In this example, we insert five command buttons and change the names to cmdInstr,
cmdLeft, cmdRight, cmdLeft, cmdMid and cmdLen respectively.

Private Sub cmdInstr_Click ()

Dim phrase As String

phrase = Cells (1, 1).Value

Cells (4, 1) = InStr (phrase, "ual")

End Sub

Private Sub cmdLeft_Click ()

Dim phrase As String

phrase = Cells (1, 1).Value

Cells (2, 1) = Left (phrase, 4)

End Sub

Private Sub cmdLen_Click ()

Dim phrase As String

phrase = Cells (1, 1).Value

Cells (6, 1) = Len (phrase)

End Sub

Private Sub cmdMid_Click ()


101
Dim phrase As String

phrase = Cells (1, 1).Value

Cells (5, 1) = Mid (phrase, 8, 3)

End Sub

Private Sub cmdRight_Click ()

Dim phrase As String

phrase = Cells (1, 1).Value

Cells (3, 1) = Right (phrase, 5)

End Sub

Figure 15.1: The end results after clicking all the command buttons.

Chapter 16
102
Date and Time Functions

Excel VBA can be programmed to handle Date and Time, adding extra capabilities to
time and date handling by MS Excel. We can use various built-in date and time
handling functions to program Excel VBA date and time manipulating programs.

16.1 Using the Now ( ) Function

The Now () function returns the current date and time according to your computer’s
regional settings. We can also use the Format function in addition to the function Now
to customize the display of date and time using the syntax Format (Now, “style

argument”). The usage of Now and Format functions are explained in the table
below:

Table 16.1: Various Date and Time Formatting with Different Style Arguments

Formatting with various style Output


arguments
Format(Now, "s") Current Time in seconds
Format(Now, "n") Current Time in minutes
Format(Now, "h") Current Time in hours
Format(Now, "m") Current Month in numeric form
Format(Now, "mmm") Current Month in short form
Format(Now, "mmmm") Current Month in full name
Format(Now, "y") Number of days to date in current year
Format(Now, "yyyy") Current Year
Example 16.1
Private Sub CommandButton1_Click ()
103
Cells (1, 1).Value = Now ()

Cells (2, 1).Value = Format (Now, "s")

Cells (3, 1).Value = Format (Now, "n")

Cells (4, 1).Value = Format (Now, "h")

Cells (5, 1).Value = Format (Now, "m")

Cells (6, 1).Value = Format (Now, "mmm")

Cells (7, 1).Value = Format (Now, "mmmm")

Cells (8, 1).Value = Format (Now, "y")

Cells (9, 1).Value = Format (Now, "yyyy")

End Sub

Figure 16.1: Output of various date and time formats

16.2 Date, Day, Weekday, WeekdayName, Month, MonthName and Year


Functions
104
The usage of these functions is illustrated in the following table:

Table 16.2: Various Date and Time functions


Function Output
Date Current date and time
Day(Date) Day part of the current date
Weekday(Date) Weekday of the current week in numeric form.
WeekdayName(Weekday(Date)) Weekday name of the current date
Month(Date) Month of the current year in numeric form
MonthName(Month(Date)) Full name of the current month
Year(Date) Current year in long form

Example 16.2

Private Sub CommandButton1_Click()

Cells(1, 1) = Date

Cells(2, 1) = Day(Date)

Cells(3, 1) = Weekday(Date)

Cells(4, 1) = WeekdayName(Weekday(Date))

Cells(5, 1) = Month(Date)

Cells(6, 1) = MonthName(Month(Date))

Cells(7, 1) = Year(Date)

End Sub
105

Figure 16.2: Output of various date and time formats.

16.3 DatePart Function

The DatePart function is used together with the Now function to obtain part of date or
time specified by the arguments. The DatePart function is generally written as

DatePart (Part of date to be returned, Now)

Various DatePart expressions and the corresponding outputs are shown in Table
16.3
Table 16.3: DatePart Expressions
DatePart Expression Part of Date /Time Returned
DatePart(“s”,Now) Current second
DatePart(“n”,Now) Current minute
DatePart(“h”,Now) Current hour
DatePart(“w”,Now) Current weekday
DatePart(“m”,Now) Current month
DatePart(“y”,Now) Current day of the year
DatePart(“yyyy”,Now) Current year
106
Example 16.3

Private Sub CommandButton1_Click ()

Cells (2, 2) = DatePart ("yyyy", Now)

Cells (3, 2) = DatePart ("m", Now)

Cells (4, 2) = DatePart ("d", Now)

Cells (5, 2) = DatePart ("w", Now)

Cells (6, 2) = DatePart ("h", Now)

Cells (7, 2) = DatePart ("n", Now)

Cells (8, 2) = DatePart ("s", Now)

End Sub

Figure 16.3: DatePart Function


107
16.4 Adding and Subtracting Dates

Dates can be added using the DateAdd function. The syntax of the DateAdd function
is

DateAdd (interval, value to be added, date)

Where interval=part of date to be added. For example, DateAdd (“yyyy”, 3, Now)


means 3 years will be added to the current year. Similarly, Dates can be subtracted
using the DateDiff function. The syntax of the DateDiff function is

DateDiff (interval, first date, second date)

Where interval=part of date to be subtracted. For example, DateDiff (“yyyy”, Now,

“6/6/2012”) means 3 years will be subtracted from the current year. Both the
aforementioned functions use the argument “s” for second, “n” for minute, “h” for hour,
“d” for day,”w” for week, “m” for month and “yyyy” for year.

Example 16.4

Private Sub CommandButton1_Click ()

Cells (1, 1) = Date


Cells (2, 1) = DateAdd ("s", 300, Now)
Cells (3, 1) = DateAdd ("n", 30, Now)
Cells (4, 1) = DateAdd ("h", 3, Now)
Cells (5, 1) = DateAdd ("d", 2, Now)
Cells (6, 1) = DateAdd ("m", 3, Now)
Cells (7, 1) = DateAdd ("yyyy", 2, Now)
Cells (8, 1) = DateDiff ("yyyy", Now, "8/6/2012")
Cells (9, 1) = DateDiff ("d", Now, "13/6/2009")
Cells (10, 1) = DateDiff ("m", Now, "8/10/2011")
Cells (11, 1) = DateDiff ("d", Now, "8/10/2009")
Cells (12, 1) = DateDiff ("n", Now, "8/10/2009")
108
Cells(13, 1) = DateDiff("s", Now, "8/10/2009")

End Sub

Figure 16.5: DateAdd and DatePart functions


109
Chapter 17
Sample Excel VBA Programs

17.1 BMI Calculator

Body Mass Index (BMI) is so popular today that it has become a standard measure
for our health status. If your BMI is too high, it means you are overweight and would
likely face a host of potential health problems associated with high BMI, such as
hypertension, heart diseases, diabetics and many others. The formula for calculating
BMI is

2
BMI=weight / (height)

The Excel VBA code for BMI calculator is illustrated below:

Private Sub CommandButton1_Click()


Dim weight, height, bmi, x As Single
weight = Cells(2, 2)
height = Cells(3, 2)
bmi = (weight) / height ^ 2
Cells(4, 2) = Round(bmi, 1)
If bmi <= 15 Then
Cells(5, 2) = "Under weight"
ElseIf bmi > 15 And bmi <= 25 Then
Cells(5, 2) = "Optimum weight"
Else
Cells(5, 2) = "Over weight"
End If

End Sub
110
The function Round is to round the value to a certain decimal places. It takes the
format Round(x, n), where n is the number to be rounded and n is the number of
decimal places. The second part of the program uses the If...Then…. Else statement
to evaluate the weight level. The output is shown in Figure 17.1

Figure 17.1: BMI Calculator

17.2: Financial Calculator

This is an Excel VBA program that can calculate monthly payment for the loan taken
from the bank. The formula to calculate periodic payment is shown below, where
PVIFA is known as present value interest factor for an annuity.

Payment=Initial Principal/PVIFA,
111
The formula to compute PVIFA is

n
1/i - 1/i (1+i)

where n is the number of payments. Normally you can check up a financial table for
the value of PVIFA and then calculate the payments manually. The function Format
is to determine the number of decimal places and the use of the $ sign. Below is the
Excel VBA code for the financial calculator:

Private Sub CommandButton1_Click()

Dim N As Integer

Dim p, pmt, rate, I, PVIFA As Double

p = Cells(2, 2)

rate = Cells(3, 2)

N = Cells(4, 2) * 12

I = (rate / 100) / 12

PVIFA = 1 / I - 1 / (I * (1 + I) ^ N)

pmt = p / PVIFA

Cells(5, 2) = Format(pmt, "$#,##0.00")

End Sub

The above financial VBA calculator can also be programmed using the built-in
worksheet function, PMT. It is very much easier to program than the previous one.
112
The format of this function is

WorksheetFunction.pmt (rate, N, amount)

Where rate is the interest rate, N is the period of payments (of number of periodic
payments) and amount is the amount borrowed.

People usually key in the annual interest rate as an integer rather than in decimal
form, so we need to divide the rate by 100 and then divide again by 12 to get the
monthly rate.

The negative sign is placed in front of the amount borrowed because this is the
amount the borrower owed the financial institute,. If we don't put the negative sign,
the payment will have a negative sign.

The VBA code is shown below:

Private Sub CommandButton1_Click ()

Dim rate, N As Integer

Dim amt, payment As Double

amt = Cells(2, 2)

rate = (Cells(3, 2) / 100) / 12

N = Cells(4, 2) * 12

payment = WorksheetFunction.pmt(rate, N, -amt)

Cells(5, 2) = Format(payment, "$##,###.00")

End Sub
113

Figure 17.2: Financial Calculator

17.3: Investment Calculator

In order to get one million dollars in the future, we need to calculate the initial
investment based on the interest rate and the length of a period, usually in years.
The formula is

WorksheetFunction.PV (rate, N, periodic payment, amount, due)

Where rate is the interest rate, N is the length of the period and amount is the amount
borrowed. Below is the Excel VBA code for the investment Calculator:
114
Private Sub CommandButton1_Click ()

Dim F_Money, Int_Rate, Investment As Double

Dim numYear As Single

F_Money = Cells(2, 2)

Int_Rate = (Cells(3, 2) / 100)

numYear = Cells(4, 2)

Investment = PV(Int_Rate, numYear, 0, F_Money, 1)

Cells(5, 2) = Format(-Investment, "$##,###,##0.00")

End Sub

Figure 17.3: Investment Calculator

17.4: Prime Number Tester


115
This Excel VBA program will test whether a number entered by the user is a prime
number or not. Prime number is a number that cannot be divided by other numbers
other than itself, it includes 2 but exclude 1 and 0 and all the negative numbers.

In this program, we use the Select Case ......End Select statement to determine
whether a number entered by a user is a prime number or not. For case 1, all
numbers that are less than 2 are not prime numbers. In Case 2, if the number is 2, it
is a prime number. In the last case, if the number N is more than 2, we divide this
number by all the numbers from 3,4,5,6,........up to N-1, if it can be divided by any of
these numbers, it is not a prime number, otherwise it is a prime number. We use the
Do......Loop While statement to control the program flow. Besides, we also used a
tag="Not Prime' to identify the number that is not prime, so that when the routine
exits the loop, the label will display the correct answer. Below is the code:

Private Sub CommandButton1_Click ()

Dim N, D As Single

Dim tag As String

N = Cells (2, 2)

Select Case N

Case Is < 2

MsgBox "It is not a prime number"

Case Is = 2

MsgBox "It is a prime number"

Case Is > 2

D=2

Do

If N / D = Int(N / D) Then
116
MsgBox "It is not a prime number"

tag = "Not Prime"

Exit Do

End If

D=D+1

Loop While D <= N - 1

If tag <> "Not Prime" Then

MsgBox "It is a prime number"

End If

End Select

End Sub

17.5 Selective Summation

This is an Excel VBA program that can perform selective summation according to a
set of conditions. For example, you might just want to sum up those figures that have
achieved sales target and vice versa. This VBA program can sum up marks that are
below 50 as well as those marks which are above 50.

In this program, rng is declared as range and we can set it to include certain range of
cells, here the range is from A1 to A10.

Then we used the For .......Next loop to scan through the selected range

rng.Cells(i).Value read the value in cells(i) and then passed it to the variable mark.

To do selective addition, we used the statement Select Case....End Select


117
Finally, the results are shown in a message box

Here is the code:

Private Sub CommandButton1_Click ()

Dim rng As Range, i As Integer

Dim mark, sumFail, sumPass As Single

sumFail = 0

sumPass = 0

Set rng = Range("A1:A10")

For i = 1 To 10

mark = rng.Cells(i).Value

Select Case mark

Case Is < 50

sumFail = sumFail + mark

Case Is >= 50

sumPass = sumPass + mark

End Select

Next i

MsgBox "The sum of Failed marks is" & Str(sumFail) & vbCrLf &

"The sum of Passed marks is" & Str(sumPass)

End Sub

También podría gustarte