Microsoft Office Tutorials and References
In Depth Information
An Introductory Example Function Procedure
h The next four lines make up a For-Next loop. The statements between the For
statement and the Next statement are executed a number of times; the value of
CellLength determines the number of times. For example, assume that the cell passed
as the argument contains the text Bob Smith . The statements within the loop would
execute nine times, one time for each character in the string.
h Within the loop, the Character variable holds a single character that is extracted using
the VBA Mid function (which works just like Excel’s MID function). The If statement
determines whether the character is not a space. (The VBA Chr function is equivalent to
Excel’s CHAR function, and an argument of 32 represents a space character.) If the
character is not a space, the character is appended to the string stored in the Temp variable
(using an ampersand, the concatenation operator). If the character is a space, the Temp
variable is unchanged, and the next character is processed. If you prefer, you can replace
this statement with the following:
If Character <> “ “ Then Temp = Temp & Character
h When the loop finishes, the Temp variable holds all the characters that were originally
passed to the function in the cell argument, except for the spaces.
h The string contained in the Temp variable is assigned to the function’s name. This string is
the value that the function returns.
h The Function procedure ends with an End Function statement.
The REMOVESPACES procedure uses some common VBA language elements, including
h A Function declaration statement
h A comment (the line preceded by the apostrophe)
h Variable declarations
h Three assignment statements
h Three built-in VBA functions ( Len , Mid , and Chr )
h A looping structure ( For-Next )
h An If-Then structure
h String concatenation (using the & operator)
Not bad for a first effort, eh? The remainder of this chapter provides more information on these
(and many other) programming concepts.
The REMOVESPACES function listed here is for instructional purposes only. You can
accomplish the same effect by using the Excel SUBSTITUTE function, which is much
more efficient than using a custom VBA function. The following formula, for example,
removes all space characters from the text in cell A1:
=SUBSTITUTE(A1,” “,””)
Search JabSto ::

Custom Search