Excel 2007 Formulas (Mr. Spreadsheets Bookshelf)

 Download CD Content

This chapter discusses some of the key language elements and programming concepts in VBA. If you've used other programming languages, much of this information may sound familiar. VBA has a few unique wrinkles, however, so even experienced programmers may find some new information.

This chapter does not even come close to being a comprehensive guide to VBA. Motivated readers will consult the Help system and make use of Internet resources or other books for additional information.

On the CD 

Many of the code examples in this chapter are on the companion CD-ROM. The file is named  function examples.xlsm.

An Introductory Example Function Procedure

To get the ball rolling, I'll begin with an example Function procedure. This function, named REMOVESPACES, accepts a single argument and returns that argument without any spaces. For example, the following formula uses the REMOVESPACES function and returns ThisIsATest.

=REMOVESPACES("This Is A Test")

To create this function, insert a VBA module into a project, and then enter the following Function procedure into the code window of the module:

Function REMOVESPACES(cell) As String ' Removes all spaces from cell Dim CellLength As Integer Dim Temp As String Dim Characters As String Dim i As Integer CellLength = Len(cell) Temp = "" For i = 1 To CellLength Character = Mid(cell, i, 1) If Character <> Chr(32) Then Temp = Temp & Character Next i REMOVESPACES = Temp End Function

Look closely at this function's code line by line:

The REMOVESPACES procedure uses some common VBA language elements, including

Not bad for a first effort, eh? The remainder of this chapter provides more information on these (and many other) programming concepts.

Note 

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," ","")

Категории