Sie sind auf Seite 1von 14

Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Macro and Visual Basic in Excel


One of the best features of Visual Basic is that it is a powerful scripting
language for writing macros and extensions to other programs including
Excel, AutoCAD, and ArcView. This tool is called Visual Basic for Applications
(VBA). This document gives a basic introduction on how to use VBA with
Excel.

Contents
1. Getting Started
a. The Visual Basic Toolbar
b. Design Mode vs. Run Mode
c. The VB Editor

2. Adding Controls to a Spreadsheet

3. Working with Cells and Ranges


a. The Range Object
b. The Cells object
c. Working with Multiple Cells
d. Looping Through Cells

4. Recording Macros

5. Trapping for Worksheet Events


a. Workbooks and Worksheets
b. The Calculate and Change Events
c. Checking on the Target
6. Creating Custom Functions
a. Format
b. Examples
c. Using Functions in VB

7. Calling Excel Worksheet Functions from VB Code

8. Custom Graphics
9. Getting Help

1. Getting Started
Writing VBA code for Excel is easy and fun!! Once you learn a few
basics, you will be creating highly professional spreadsheets. VBA
allows you to design a spreadsheet that will do things that are
impossible with the basic spreadsheet options. It also allows you to
make your spreadsheets more user-friendly.

The Visual Basic Toolbar


The first step in adding Visual Basic to your spreadsheet is to turn on
the VB Toolbar. To turn on the toolbar, select the View menu, click on
the Toolbars command, and turn on the Visual Basic option. The following
toolbar will appear:

The options in the toolbar are as follows:


These buttons are used to run VB macros.

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 1/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

These buttons are used to record VB macros.


This option is used to establish the security settings for the VB code. VB
macros can be used to write computer viruses. The security settings
are used to minimize danger from such viruses.
This tool displays the Visual Basic Editor. This is where you write the
Visual Basic code.
This tool displays the Control Toolbar. This toolbar is used to add VB
controls such as check boxes, combo boxes, and radio groups to a
spreadsheet.
This tool is used to toggle the spreadsheet in and out of Design Mode.
This option brings up the spreadsheet (both the spreadsheet and any
underlying VB code in the Microsoft Development Environment. This
editor allows you to edit the underlying spreadsheet code in an HTML
format and develop powerful web applications.
Design Mode
When you are writing VB code and adding controls to a spreadsheet, there
are two basic modes: Design mode and Run mode. In design mode, when you
click on a button or a control, you can edit the properties of the
control in the VB Editor. If you double click on a control, you can edit
the code associated with the control. If you are in Run mode, when you
click on the control, the code associated with the control is executed.
When developing your spreadsheet, you will be moving in and out of Design
mode.

The VB Editor
The VB Editor is where you edit the Visual Basic code. It is very similar
to the regular Visual Basic compiler. The code is shown in a set of
windows on the right. The Project window on the left lists the components
of the project. The Microsoft Excel Objects folder lists each of the sheets
in your spreadsheet and the workbook. The Modules folder lists the code
associated with Macros.

2. Adding Controls to a Spreadsheet


To add a control to a spreadsheet, simply select a control in the Control
Toolbar and create the tool in the spreadsheet, just like you would create
a control on a form in the Visual basic editor. Once you create the
control, right click on it and select the Properties option. This will
bring up the Properties window. Once this window is open, it refreshes
automatically each time you select a control. To edit the code
associated with a control, simply double click on the control.
The controls behave similarly to the controls in the regular VB compiler,
but there are some differences. For example, when you create a combo box
in the VB compiler, there is a "List" field in the Properties where you
can type in the components of the list. In VBA for Excel, there is no
"List" field but there is a "ListFillRange" field. To define the list,
you need to enter the list items in some cells somewhere on the
spreadsheet. Typically, you use one of the extra sheets in the
background for this type of information. For example, if I have a sheet
called "Extra" where I have defined the list items, I would type "Extra!
C5:C7" in the ListFillRange field.

3. Working with Cells and Ranges

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 2/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

When writing VB code, you can use variables, for loops, and all other VB
types and statements. However, most of your code will be dealing with
values stored in cells and ranges.

The Range Object


A range is set of cells. It can be one cell or multiple cells. A range
is an object within a worksheet object. For example, the following
statement sets the value of cell C23 to a formula referencing a set of
named cells:

Worksheets("Sheet3").Range("C23").Value = "=5^(1/2)"

If the " Sheet3" worksheet is the active sheet, the first part can be
left off as follows:

Range("C23").Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

The ".Value" part is optional. You can also write:

Range("C23") = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

You have to remember to put the double quotes around the cell address.
If the cell C23 has been named "Q" in the spreadsheet, you can reference
the range as follows:

Range("Q").Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

To get something from a cell and put it in a variable, you just do things
in reverse:

x = Range("B14").Value

If X is a double or integer, you may also want to use the Val function:

x = val(Range("B14").Value)

The Cells Object


Another way to interact with a cell is to use the Cells(rowindex,
columnindex) function. For example:

Cells(2, 5).Value = "=(u/n)*A*Rh^(2/3)*S^(1/2)"

or

x = val(Cells(2, 14).Value)

Once again, the value part is optional since it is the default property
of both the cell and range object.

Working with Multiple Cells


A range can also encompass a set of cells. The following code selects a
block of cells:
Range("A1:C5").Select
or
Range("A1", "C5").Select
In some cases, it is useful to reference a range of cells using integers
representing the row and column of the cell. This can be accomplished
with the Cells object. For example:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 3/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Range(Cells(1,1), Cells(3,5)).Select
The problem with referring to specific cells in your code is that if you
change the location of data on your spreadsheet, you need to go through
your code and make sure all of the addresses are updated. In some cases
it it useful to define the ranges you are dealing with using global
constants at the top of your VB code. Then when you reference a range,
you can use the constants. If the range ever changes, you only need to
update your code in one location. For example:

Const TableRange As String = "A4:D50"


Range(TableRange).ClearContents
.
.

An even better approach is to get into the habit of naming cells and
ranges on your spreadsheet. Then your VB code can always refer to ranges
by names. Then, if you change the location or domain of a named range,
you generally don't need to update your VB code. For example:

.
.
Range("TableRange").ClearContents
Range("NameRange").ClearContents
Range("ScoreRange").ClearContents
.
.

Looping Through Cells


One of the most common things we do with VB code is to traverse or loop
through a set of cells. There are several ways this can be
accomplished. One way is to use the Cells object. The following code
loops through a table of cells located in the range B4:F20:
Dim row As Integer
Dim col As Integer

For row = 4 To 20
For col = 2 To 6
If Cells(row, col) = "" Then
Cells(row, col).Interior.Color = vbRed
End If
Next col
Next row
In most cases, it doesn't matter what order the cells are traversed, as
long as each cell is visited. In such cases the For Each ... Next
looping style may be used. The following code does the same thing as the
nested loop shown above:

Dim cell As Variant

For Each cell In Range("B4:F20")


If cell = "" Then
cell.Interior.Color = vbRed
End If
Next cell

Another option is to create your own range objects. A range object is


essentially a range type variable. The following code defines three
ranges:

Dim coordrange As Range


Dim xrange As Range

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 4/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Dim yrange As Range

Set xrange = Range(Cells(3, 1), Cells(100, 1))


Set yrange = Range(Cells(3, 2), Cells(100, 2))
Set coordrange = Range(Cells(3, 1), Cells(100, 2))

Once a set of range objects has been defined, you can easily manipulate
the cells in the range object. For example, the following code clears
the contents of all the cells in the coordrange object:
coordrange.Clear
Once again, these ranges can be traversed using the For Each ... Next
syntax.

Dim cell As Variant

For Each cell In xrange


cell.Value = "0.0"
Next cell

One of the most useful things you can do with VBA in Excel is to allow
the user to enter a list of numbers where the size of the list can vary.
The following code searches through a list and copies the numbers in the
list into an array. It stops copying the numbers when it reaches a blank
cell.

'Get the x values


i = 0
For Each cell In Range("B4:B23")
If cell.Value = "" Then
numpts = i
Exit For
Else
i = i + 1
x(i) = Val(cell.Value)
End If
Next cell

4. Recording Macros
A VB Macro is essentially a VB subroutine that executes a series of VB
statements. To generate a macro, click on the Record Macro button in
the VB Toolbar. You will then be prompted for the name of the macro.
Then you select a series of menu commands and/or make changes to your
spreadsheet. When finished, you select the Stop Recording button . To
view the code associated with the macro, go to the Project window, expand
the Modules folder and double click on the Module1 item.
Macros are extremely useful when you are first learning how to write VBA
code in Excel. If you want to do something in code such as change the
background color of a cell, but you don't know to do it, simply run a
macro, change the color manually, and then look at the macro. You can
learn how to do just about anything simply by running macros.

5. Trapping for Worksheet Events


When writing VB code associated with a spreadsheet, it is common to add a
button to the spreadsheet that the user pushes to execute the VB code
when the desired changes have been made to the controls and the values
have been entered in the cells. For example, the following code performs
some simple tests to see if someone is ready to take the Research
Qualification test:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 5/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

In this case, we don't need any code for the click events for the option
and checkbox controls. We simply need to add the following code for the
"Do I Qualify" button:

This code works fine, but why require the user to click on the button?
Why not set up the spreadsheet so that anytime the user clicks on a
control or changes the value of a cell, the VB code is automatically
executed and the results are updated? This can be easily accomplished
using the "Change" event for the worksheet.

Workbooks and Worksheets


Before discussing the Change event, we need to first define a couple of
terms. When the VB compiler for Excel is open, you will see a list of
objects in a tree on the left side of the window. At the bottom of the
tree you will see the following objects:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 6/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

A "Workbook" object represents the entire spreadsheet, including all of


the sheets. If you double click on this object, it will bring up the
source code related to the workbook as a whole. The other objects
("Sheet1", "Sheet2", & "Sheet3"). Double clicking on these objects
brings up the code related to these objects.
Once you open the window related to a particular sheet, some important
information related to the sheet is displayed at the top of the sheet as
follows:

The combo box on the left (the one that is open) lists all of the objects
associated with the sheet. Note that each of the controls on the
spreadsheet are listed along with the worksheet itself. If you highlight
one of the objects, you can then select an event from the combo box on
the right:

Selecting one of these events creates the subroutine for the selected
event. For example, if I click on the "Change" item, the following code
appears:

The Calculate and Change Events


Note that the list of available events for the worksheet include the
"Calculate" event and the "Change" event. By selecting these items, we
can then fill in the code for these events. The resulting code will be
executed as follows:

Calculate Event
The Calculate event looks like this:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 7/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

and is called each time the formulas in the worksheet are recalculated.
Note that you must have at least one formula in your spreadsheet in order
for this event to be called.

Change Event
The change event looks like this:

and is called each time any of the cells in the spreadsheet are changed.
Note that the subroutine takes one argument which is the range that has
been changed. If we want the spreadsheet to be updated any time the user
enters new data, this is the event we want to use. First of all, we
remove the button so that the spreadsheet looks as follows:

Next, we will modify the code in the Change event to update the
spreadsheet. However, this event is not called when a control is
changed, it is only called when a cell is changed. Therefore, we will
first create a subroutine that performs the calculations:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 8/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Next, we will modify the Change event so that it calls this subroutine:

Finally, to ensure that the click events for the controls cause the
results to be updated, we add a call to the click event subroutines for
each of the controls as follows:

At this point, clicking on any of the controls, or updating the value in


the "years" cell triggers the VB code to update the results.

Checking on the Target

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 9/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Note that in the code for the Worksheet_Change event, we must do a check
to determine which cells have changed. If we simply call the
Update_Results subroutine every time the Change event is called, we will
get an infinite loop. This is because the Update_Results subroutine ends
up changing the cells in the range B13 and B15:B17. This causes a Change
event, which then calls Update_Results again, which causes another Change
event, etc. etc. If we only call the Update_Results subroutine if the
"years" cell is changed, we can ensure that we don't cause an infinite
loop. Another way to handle this is to check to ensure that the target
cell is not one of the output cells. For example:

While this approach is fairly simple and it works in most cases, it does
have two flaws. First of all, this method is cumbersome when either the
input range or the output range contains a large number of cells.
Second, as a range object, Target may correspond to one cell or multiple
cells. If Target contains one cell, the two versions of the
Worksheet_Change sub shown above will work fine. However, in some cases
the user may change multiple cells at once. For example, the user may
select a set of cells and press the Delete key to clear the contents of
the cells. In this case, Target will contain a multi-cell range and
statements of the form:

Target = Range("B4")

Or

Target <> Range ("B13")

will generate an error message. A more efficient and robust approach is


to use the Intersect method associated with the Application object. This
method returns the intersection between two ranges. The idea is to
intersect the target range and the range corresponding to the input cells
and see if the result is non-empty. This can be accomplished as follows:

This approach will work with input ranges spanning multiple cells. For
example:

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 10/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

6. Custom Functions
One of the easiest ways to take advantage of VBA in Excel is to write
custom functions. Excel has a large number of built-in functions that
you can use in spreadsheet formulas. Examples include:

=Average("A4:A20")Returns the average value in a range of cells


=Sum("A4:A20") Returns the sum of a range of cells
=Cos(0.34) Returns the cosine of a number

In general, a function takes one or more objects (values, ranges, etc.)


as input and returns a single object (typically a value). The things
that are sent to a function as input are called arguments and the thing
that is returned by a function is often called the return value.
In some cases, we may encounter situations where we need a function to do
something but the function is not provided by Excel. We can easily fix
this problem by creating a custom function in VBA.

Format
The basic format for a custom function is as follows:

[Public] Function function_name(args) As Type


...
function_name = ...
...
End Function

The Public statement is optional. This means that the function can be
called by VB code outside the module where the function is declared and
from Excel formulas in cells. If you omit the Public statement, the
function is public by default (as opposed to Private).
The function_name is the name you provide to the function. This can be
any name you want, as long as you follow the same rules we use for
defining VB variable names.
The args are the arguments to the function. You can have any number of
arguments. The arguments are listed in the same way you declare
variables, except that you omit the Dim part. The args list serves two
purposes: 1) it defines how many arguments are used, and 2) it defines
the type for each argument. The following are some sample argument
lists:

(x As Double, n As Double)
(r As Range)
(str1 As String, str2 As String, num As Integer)

The Type part defines the type of object returned by the function.
Typical examples are Double, Integer, String, and Boolean.
Somewhere in the code, you must have line where you set the function name
equal to a value. You should think of the function name as a variable.
You must store the value returned by the function in the variable at some
point before you hit the End Function statement.
There is one more important point, whenever you create a function that
you want to use in an Excel formula, it should always be placed in a
module under the Modules folder in the VBE.

Examples
Now let's look at some examples. The following function takes two
numbers as arguments and returns the minimum of the two numbers. This
basically duplicates the Min function provided by Excel, but it serves as
a useful example:

Function my_min(a As Double, b As Double) As Double

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 11/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

If a < b Then
my_min = a
Else
my_min = b
End If
End Function

Once this function is created, you can then use it in one of your Excel
formulas as follows:

=my_min(A5, B7)
=my_min(Sum(C3:C10), 0)

Now let's look at something a little more complicated. In many cases, we


want our function to use a cell range as one of the arguments. The
following function returns the number of negative values in a range:

Function num_neg(r As Range) As Integer


Dim c As Variant
For Each c In r
If c.Value < 0 Then
num_neg = num_neg + 1
End If
Next c
End Function

The function could then be called from an Excel formula as follows:

=num_neg(A5:B7)

The next function takes two arguments: a range and an integer n. It


computes the sum of values in the range minus the lowest n values. This
function takes advantage of the standard Excel functions Sum and Small.
The Small function returns the nth lowest value in a range.

Function dropsum(r As Range, n As Integer) As Double


Dim i As Integer
dropsum = Application.WorksheetFunction.Sum(r)
For i = 1 To n
dropsum = dropsum - Application.WorksheetFunction.Small(r,
i)
Next i
End Function

This function could then be used in an Excel formula as follows:

=dropsum(A5:B7, C10)
=dropsum(A5:B7, 5)
Functions in VB
Finally, it should be noted that you can call custom functions from other
places in your VB code as well as from Excel formulas. For example, you
could use the my_min function defined above as follows:
Dim x As Double
Dim y As Double
Dim z As Double
x = ...
y = ...
...

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 12/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

z = my_min(x, y)
...

7. Calling Excel Functions from VB Code


One of the nice things about writing VB code inside Excel is that you can
combine all of the power and flexibility of Visual Basic with the many
tools and options in Excel. One of the best examples of this is that you
can take advantage of all of the standard Excel worksheet functions
inside your VB code. Calling an Excel worksheet function is simple. The
Excel functions are available as methods within the WorksheetFunction
object. You simply invoke the method and pass the arguments that the
function requires (typically a range).
For example, if we were writing a simple formula to put in a cell to find
the maximum value in a range of cells, we would write the following:

=Min(B4:F30)

The following code uses the same Min function, but invokes the function
using VB code. The min value is stored in a variable called minval:

Dim minval As Double


minval = Application.WorksheetFunction.Min(Range("B4:F30"))

Notice the difference in how the range is specified. In the VB code, the
range is specified as a range object.
The Application. portion is actually optional and can be omitted in most
cases. Thus, the following code achieves the same thing:

Dim minval As Double


minval = WorksheetFunction.Min(Range("B4:F30"))

Here are some more examples:

Range("e5") = WorksheetFunction.sum(Range("b5:b29"))

'This is useful since VB does not have an inverse sin


function
Dim x As Double
x = WorksheetFunction.Asin(0.223)

Dim i As Integer
i = 5
Range("H4") = WorksheetFunction.Fact(i)

8. Custom Graphics
A common task faced by programmers is how to display custom graphics
using source code. It is often useful to display an object that is
properly dimensioned in terms of the input parameters supplied on the
user. For example, one could display the geometry of a cantilever beam
or a column based on the user input. At the other end of the spectrum,
it is possible to write sophisticated computer programs with 3D graphics
and animation.

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 13/14
Quản lý quan hệ số liệu môi trường Thực hành: Sử dụng Macro trongMS Excel

Standard VB (applied to a VB form) has a simple, yet powerful set of


graphics options. You create a Picture object and then use a series of
commands to draw lines and simple shapes in the Picture object. However,
none of these tools can used for VBA in Excel. With Excel, an entirely
different approach must be used. This approach involves a special type
of object called a "Shape". Shapes can be created manually by the user

of the spreadsheet using the standard MS Office drawing toolbar:

Any of the graphical objects in this menu (lines, connectors, basic


shapes, etc.) are classified as shapes. Once created, they can be
manipulated via VB code. Since the basic shapes include lines,
rectangles, circles, and polygons, you can create just about any custom
drawing that you can think of.

9. To Get Help
To learn more about using VBA in Excel, bring up the Help file and go to
the Contents section. Open up the Programming Information topic and then
open up the Microsoft Excel Visual Basic Reference topic.

1 12
2 23
3 23
4 25
5 34

Thiết kế Thí nghiệm và Xử lý Số liệu trong Môi trường 14/14

Das könnte Ihnen auch gefallen