11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 24: VBA Programming Concepts 637<br />

The next four lines make up a For-Next loop. The statements between the For<br />

statement and the Next statement are executed a number of times; the value of<br />

CellLength determines the number of times. For example, assume that the cell passed<br />

as the argument contains the text Bob Smith. The statements within the loop would<br />

execute nine times, one time for each character in the string.<br />

Within the loop, the Character variable holds a single character that is extracted using<br />

the VBA Mid function (which works just like Excel’s MID function). The If statement<br />

determines whether the character is not a space. (The VBA Chr function is equivalent to<br />

Excel’s CHAR function, and an argument of 32 represents a space character.) If the character<br />

is not a space, the character is appended to the string stored in the Temp variable<br />

(using an ampersand, the concatenation operator). If the character is a space, the Temp<br />

variable is unchanged, and the next character is processed. If you prefer, you can replace<br />

this statement with the following:<br />

If Character “ “ Then Temp = Temp & Character<br />

When the loop finishes, the Temp variable holds all the characters that were originally<br />

passed to the function in the cell argument, except for the spaces.<br />

The string contained in the Temp variable is assigned to the function’s name. This string is<br />

the value that the function returns.<br />

The Function procedure ends with an End Function statement.<br />

The REMOVESPACES procedure uses some common VBA language elements, including<br />

A Function declaration statement<br />

A comment (the line preceded by the apostrophe)<br />

Variable declarations<br />

Three assignment statements<br />

Three built-in VBA functions (Len, Mid, and Chr)<br />

A looping structure (For-Next)<br />

An If-Then structure<br />

String concatenation (using the & operator)<br />

Not bad for a first effort, eh? The remainder of this chapter provides more information on these<br />

(and many other) programming concepts.<br />

The REMOVESPACES function listed here is for instructional purposes only. You can<br />

accomplish the same effect by using the Excel SUBSTITUTE function, which is much<br />

more efficient than using a custom VBA function. The following formula, for example,<br />

removes all space characters from the text in cell A1:<br />

=SUBSTITUTE(A1,” “,””)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!