Wrox Beginning Tutorial Ebooks - Excel 2007 Vba Programmers Reference - 2
Wrox Beginning Tutorial Ebooks - Excel 2007 Vba Programmers Reference - 2
Many users assume that this declares each variable to be Integer. This is not true. Coland Roware Variantbecause they have not been given a type. To declare all three as Integer, the line should be as follows: Dim Col As Integer, Row As Integer, Sheet As Integer
Constants
You have seen that many intrinsic constants are built into VBA, such as vbYesand vbNo,discussed previously. You can also define your own constants. Constants are handy for holding numbers or pieces of text that do not change while your code is running, but that you want to use repeatedly in calculations and messages. Constants are declared using the Constkeyword, as follows: Const Pi = 3.14159265358979 You can include the constants type in the declaration: Const Version As String = Release 3.9a Constants follow the same rules regarding scope as variables. If you declare a constant within a procedure, it will be local to that procedure. If you declare it in the declarations section of a module, it will be available to all procedures in the module. If you want to make it available to all modules, you can declare it to be Publicas follows: Public Const Error666 As String = You cant do that
44
Object Variables
The variables you have seen so far have held data such as numbers and text. You can also create object variables to refer to objects such as worksheets and ranges. The Setstatement is used to assign an object reference to an object variable. Object variables should also be declared and assigned a type as with normal variables. If you dont know the type, you can use the generic term Objectas the type: Dim objWorkbook As
Object Set objWorkbook = ThisWorkbook MsgBox objWorkbook.Name It is more efficient to use the specific object type if you can. The following code creates an object variable rng,referring to cell B10 in Sheet1, in the same workbook as the code. It then assigns values to the object and the cell above: Sub ObjectVariable() Dim rng As Range Set rng = ThisWorkbook.Worksheets(Sheet1).Range(C10) rng.Value = InputBox(Enter Sales for January) rng.Offset(1, 0).Value = January Sales End Sub If you are going to refer to the same object more than once, it is more efficient to create an object variable than to keep repeating a lengthy specification of the object. It also makes code easier to read and write.
45