Beruflich Dokumente
Kultur Dokumente
Contents
1. Getting Started
a. The Visual Basic Toolbar
b. Design Mode vs. Run Mode
c. The VB Editor
4. Recording Macros
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.
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
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.
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.
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)"
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)
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.
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:
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
.
.
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:
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
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.
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.
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.
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.
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
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:
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:
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
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:
Format
The basic format for a custom function is as follows:
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:
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)
=num_neg(A5:B7)
=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)
...
=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:
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:
Range("e5") = WorksheetFunction.sum(Range("b5:b29"))
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
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