Microsoft Office Tutorials and References
In Depth Information
2.2.3 Modularity
' Reverses a string
FUNCTION Reverse$ (aname$)
Temp$ = ""
FOR i = LEN(aname$) TO 1 STEP -1
Temp$ = Temp$ + MID$(aname$, i, 1)
Reverse$ = Temp$
Of course, the saving in space is not great in this example, but you can imagine what would
happen if we replace the reversing procedure by one that requires several hundred lines of code
and if we want to perform this procedure a few hundred times in the main program. This
modularization could save thousands of lines of code.
There is another very important advantage to modular programming. If we decide to write another
program that requires reversing some strings, we can simply add our string-reversing code module
to the new program, without having to write any new code. Indeed, professional programmers
often compile custom code libraries containing useful code modules that can be slipped into new
applications when necessary.
It is hard to overestimate the importance of modular programming. Fortunately, as we will see,
VBA makes it easy to create modular programs.
Generally speaking, there are two main groups of code modules: functions and subroutines . The
difference between them is that functions return a value whereas subroutines do not. (Of course,
we may choose not to use the value returned from a function.) For instance, the Reverse function
described in the previous example returns the reversed string. On the other hand, the following
code module performs a service but does not return a value—it simply pauses a certain number of
seconds (given by sec ):
SUB delay (sec)
' Get the current time
StartTime = TIMER
' Enter a do-nothing loop for sec seconds
LOOP UNTIL TIMER - StartTime > sec
Functions and subroutines are extremely common in modern coding. Together, they are referred to
as procedures .
Search JabSto ::

Custom Search