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 641<br />

Unlike some languages, VBA does not permit you to declare a group of variables to<br />

be a particular data type by separating the variables with commas. For example, the<br />

following statement — although valid — does not declare all the variables As Longs:<br />

Dim i, j, k As Long<br />

In the preceding statement, only k is declared to be an integer. To declare all variables<br />

As Longs, use this statement:<br />

Dim i As Long, j As Long, k As Long<br />

If you don’t declare the data type for a variable that you use, VBA uses the default data type —<br />

Variant. Data stored as a variant acts like a chameleon: It changes type depending on what you<br />

do with it. The following procedure demonstrates how a variable can assume different data types:<br />

Function VARIANT_DEMO()<br />

MyVar = “123”<br />

MyVar = MyVar / 2<br />

MyVar = “Answer: “ & MyVar<br />

VARIANT_DEMO = MyVar<br />

End Function<br />

In the VARIANT_DEMO Function procedure, MyVar starts out as a three-character text string<br />

that looks like a number. Then this string is divided by two, and MyVar becomes a numeric data<br />

type. Next, MyVar is appended to a string, converting MyVar back to a string. The function<br />

returns the final string: Answer: 61.5.<br />

You’ll notice that I don’t follow my own advice in this chapter. In many of the subsequent<br />

function listings in this chapter, I don’t declare the variables used. I omitted the<br />

variable declarations to keep the code simple so that you can focus on the concept<br />

being discussed. In the code examples on the companion CD-ROM, I always declare<br />

the variables.<br />

Using constants<br />

A variable’s value may — and often does — change while a procedure is executing. That’s why it’s<br />

called a variable. Sometimes, you need to refer to a named value or string that never changes: in<br />

other words, a constant.<br />

You declare a constant by using the Const statement. Here are some examples:<br />

Const NumQuarters As Long = 4<br />

Const Rate = .0725, Period = 12<br />

Const CompanyName as String = “Acme Snapholytes”

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

Saved successfully!

Ooh no, something went wrong!