Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 99 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
99
Dung lượng
825,09 KB
Nội dung
159 Chapter 7 ✦ Introducing Visual Basic for Applications Table 7-2 Methods of a Comment Object Method Description Delete Deletes a comment. Next Returns a Comment object that represents the next comment. Previous Returns a Comment object that represents the previous comment. Text Returns or sets the text in a comment (takes three arguments). You may be surprised to see that Text is a method rather than a property. This leads to an important point: The distinction between properties and methods isn’t always clear-cut, and the object model isn’t perfectly consistent. In fact, it’s not really important that you distinguish between properties and methods. As long as you get the syntax correct, it doesn’t matter if a word in your code is a property or a method. The Comments collection Recall that a collection is a group of like objects. Every worksheet has a Comments collection, which consists of all Comment objects on the worksheet. If the worksheet has no comments, this collection is empty. For example, the following code refers to the first comment on Sheet1 of the active workbook: Worksheets(“Sheet1”).Comments(1) The following statement displays the text contained in the first comment on Sheet1: MsgBox Worksheets(“Sheet1”).Comments(1).Text Unlike most objects, a Comment object does not have a Name property. Therefore, to refer to a specific comment you must use an index number, or use the Comment property of a Range object to return a specific comment (keep reading, and this will make sense). The Comments collection is also an object and has its own set of properties and methods. For example, the following example shows the total number of comments: MsgBox ActiveSheet.Comments.Count Note 4799-2 ch07.F 6/11/01 9:29 AM Page 159 160 Part III ✦ Understanding Visual Basic for Applications The Comments collection here has a Count property that stores the number of Comment objects in the active worksheet. The next example shows the address of the cell that has the first comment: MsgBox ActiveSheet.Comments(1).Parent.Address Here, Comments(1) returns the first Comment object in the Comments collection. The Parent property of the Comment object returns its container, which is a Range object. The message box displays the Address property of the Range. The net effect is that the statement displays the address of the cell that contains the first comment. You can also loop through all the comments on a sheet by using the For Each-Next construct (this is explained in Chapter 8). Here’s an example that displays a sepa- rate message box for each comment on the active worksheet: For Each cmt in ActiveSheet.Comments MsgBox cmt.Text Next cmt If you’d rather not deal with a series of message boxes, use this procedure to print the comments to the Intermediate window in the VBE: For Each cmt in ActiveSheet.Comments Debug.Print cmt.Text Next cmt About the Comment property In this section I’ve been discussing the Comment object. If you dig through the online help, you’ll find that a Range object has a property named Comment. If the cell contains a comment, the Comment property returns an object: a Comment object. For example, the following statement refers to the Comment object in cell A1: Range(“A1”).Comment If this were the first comment on the sheet, you could refer to the same Comment object as follows: Comments(1) To display the comment in cell A1 in a message box, use a statement like this: MsgBox Range(“A1”).Comment.Text If cell A1 does not contain a comment, this statement will generate an error. The fact that a property can return an object is a very important concept — a diffi- cult one to grasp, perhaps, but critical to mastering VBA. Note 4799-2 ch07.F 6/11/01 9:29 AM Page 160 161 Chapter 7 ✦ Introducing Visual Basic for Applications Objects within a Comment object Working with properties is confusing at first because some properties actually return objects. Suppose that you want to determine the background color of a par- ticular comment on Sheet1. If you look through the list of properties for a Comment object, you won’t find anything that relates to color. Rather, you must do this: 1. Use the Comment object’s Shape property to return the Shape object that’s contained in the comment. 2. Use the Shape object’s Fill property to return a FillFormat object. 3. Use the FillFormat object’s ForeColor property to return a ColorFormat object. 4. Use the ColorFormat object’s RGB property (or SchemeColor property) to set the color. Put another way, getting at the interior color for a Comment object involves access- ing other objects contained in the Comment object. Here’s a look at the object hier- archy that’s involved. Application (Excel) Workbook object Worksheet object Comment object Shape object FillFormat object ColorFormat object I’ll be the first to admit it: This can get very confusing! But, as an example of the “elegance” of VBA, code to change the color of a comment can be written with a single statement: Worksheets(“Sheet1”).Comments(1).Shape.Fill.ForeColor _ .RGB = RGB(0, 255, 0) Or, if you use the SchemeColor property (which ranges from 0 to 80): Worksheets(“Sheet1”).Comments(1).Shape.Fill.ForeColor _ .SchemeColor = 12 This type of referencing is certainly not intuitive at first, but it will eventually make sense. Fortunately, recording your actions in Excel almost always yields some insights regarding the hierarchy of the objects involved. 4799-2 ch07.F 6/11/01 9:29 AM Page 161 162 Part III ✦ Understanding Visual Basic for Applications By the way, to change the color of the text in a comment, you’ll need to access the Comment object’s TextFrame object, which contains the Characters object, which contains the Font object. Then, you’ll have access to the Font object’s Color or ColorIndex properties. Here’s an example that sets ColorIndex property to 5: Worksheets(“Sheet1”).Comments(1) _ .Shape.TextFrame.Characters.Font.ColorIndex = 5 Confused by Colors? As you gain experience with VBA and start working with setting colors for various objects, you will probably reach a head-scratching point and wonder what’s going on. Keep this in mind: Excel uses a 56-color palette of colors, and the specific colors are saved with each workbook. These are the colors you see when you use the Fill Color button on Excel’s Formatting toolbar (the same colors that are displayed in the Color tab of the Options dia- log box). So what does this mean for a VBA programmer? The color you specify in your VBA code may or may not be the color that actually appears. Things get even more confusing. Depending on the object you’re manipulating, you’ll need to deal with several different color-related objects and properties. You can set the color of a Shape object by using either the RGB property or the SchemeColor property. The RGB property lets you specify a color in terms of its red, green, and blue components. This is used in conjunction with VBA’s RGB function, which takes three arguments, each of which ranges from 0 to 255. The RGB function returns a value between 0 and 16,777,215. But, as I mentioned, Excel can only handle 56 different colors. Therefore, the actual color that results when you use the RGB function will be the closest color match in the workbook’s 56-color palette. The SchemeColor property accepts values between 0 and 80. The online help says virtually nothing about what these colors actually represent. They are, however, limited to the workbook’s color palette. When you’re dealing with colors in a Range object, you need to access the Interior object, contained in the Range object. You have a choice of setting the color using the Color property or the ColorIndex property. Valid values for the ColorIndex property are 0 through 56 (0 represents no fill). These values correspond to the workbook’s color palette. Unfortunately, the order of the colors displayed bears no relationship to the num- bering system for the ColorIndex property, so you’ll need to record a macro to determine the ColorIndex value for a particular color. Even then, there’s no guarantee that the user hasn’t changed the color palette for the workbook. If so, the ColorIndex may result in a color completely different from the one you had in mind. If you use the Color property, you can specify a color value using VBA’s RGB function. But, again, the actual color that you get will be the one closest to a color in the workbook’s color palette. 4799-2 ch07.F 6/11/01 9:29 AM Page 162 163 Chapter 7 ✦ Introducing Visual Basic for Applications Determining whether a cell has a comment The following statement will display the comment in cell A1 of the active sheet: MsgBox Range(“A1”).Comment.Text If cell A1 does not have a comment, executing this statement will generate a cryptic error message: Object variable or With block variable not set. To determine whether a particular cell has a comment, you can write code to see whether the Comment object is Nothing (yes, Nothing is a valid keyword). The following statement displays True if cell A1 does not have a comment: MsgBox Range(“A1”).Comment Is Nothing Note that I use the Is keyword, not an equals sign. Adding a new Comment object You may have noticed that the list of methods for the Comment object doesn’t include a method to add a new comment. This is because the AddComment method belongs to the Range object. The following statement adds a comment (an empty comment) to cell A1 on the active worksheet: Range(“A1”).AddComment If you consult the online help, you’ll discover that the AddComment method takes an argument that represents the text for the comment. Therefore, you can add a comment and then add text to the comment with a single statement, like this: Range(“A1”).AddComment “Formula developed by JW.” The AddComment method generates an error if the cell already contains a comment. If you’d like to see these Comment object properties and methods in action, check out the example workbook on the companion CD-ROM. This workbook contains several examples that manipulate Comment objects with VBA code. You probably won’t understand all the code, but you will get a feel for how you can use VBA to manipulate an object. Some useful Application properties As you know, when you’re working with Excel, only one workbook at a time can be active. And if the sheet is a worksheet, one cell is the active cell (even if a multicell range is selected). On the CD-ROM Note 4799-2 ch07.F 6/11/01 9:29 AM Page 163 164 Part III ✦ Understanding Visual Basic for Applications VBA knows this and lets you refer to these active objects in a simplified manner. This is often useful, because you won’t always know the exact workbook, work- sheet, or range that you want to operate on. VBA handles this by providing proper- ties of the Application object. For example, the Application object has an ActiveCell property that returns a reference to the active cell. The following instruction assigns the value 1 to the active cell: ActiveCell.Value = 1 Notice that I omitted the reference to the Application object in the preceding example because it is assumed. It’s important to understand that this instruction will fail if the active sheet is not a worksheet. For example, if VBA executes this statement when a chart sheet is active, the procedure halts and you’ll get an error message. If a range is selected in a worksheet, the active cell will be in a cell within the selected range. In other words, the active cell is always a single cell (never a multi- cell range). The Application object also has a Selection property that returns a reference to whatever is selected, which could be a single cell (the active cell), a range of cells, or an object such as ChartObject, TextBox, or Shape. Table 7-3 lists the other Application properties that are useful when working with cells and ranges. Table 7-3 Some Useful Properties of the Application Object Property Object Returned ActiveCell The active cell ActiveChart The active chart sheet or chart object on a worksheet. This property will be Nothing if a chart is not active. ActiveSheet The active sheet (worksheet or chart) ActiveWindow The active window ActiveWorkbook The active workbook RangeSelection The selected cells on the worksheet in the specified window, even when a graphic object is selected Selection The object selected (it could be a Range object, Shape, ChartObject, and so on) ThisWorkbook The workbook that contains the procedure being executed 4799-2 ch07.F 6/11/01 9:29 AM Page 164 165 Chapter 7 ✦ Introducing Visual Basic for Applications The advantage of using these properties to return an object is that you don’t need to know which cell, worksheet, or workbook is active, or provide a specific refer- ence to it. This allows you to write VBA code that is not specific to a particular workbook, sheet, or range. For example, the following instruction clears the con- tents of the active cell, even though the address of the active cell is not known: ActiveCell.ClearContents The example that follows displays a message that tells you the name of the active sheet: MsgBox ActiveSheet.Name If you want to know the name of the active workbook, use a statement like this: MsgBox ActiveWorkbook.Name If a range on a worksheet is selected, you can fill the entire range with a value by executing a single statement. In the following example, the Selection property of the Application object returns a Range object that corresponds to the selected cells. The instruction simply modifies the Value property of this Range object, and the result is a range filled with a single value: Selection.Value = 12 Note that if something other than a range is selected (such as a ChartObject or a Shape), the preceding statement will generate an error because ChartObjects and Shape objects do not have a Value property. The following statement, however, enters a value of 12 into the Range object that was selected before a non- Range object was selected. If you look up the RangeSelection property in the online help, you’ll find that this property applies only to a Window object. ActiveWindow.RangeSelection.Value = 12 To find out how many cells are selected in the active worksheet, access the Count property. Here’s an example: MsgBox ActiveWindow.RangeSelection.Count Working with Range Objects Much of the work you will do in VBA involves cells and ranges in worksheets. After all, that’s what spreadsheets are designed to do. The earlier discussion on relative versus absolute macro recording exposed you to working with cells in VBA, but you need to know a lot more. 4799-2 ch07.F 6/11/01 9:29 AM Page 165 166 Part III ✦ Understanding Visual Basic for Applications A Range object is contained in a Worksheet object, and consists of a single cell or range of cells on a single worksheet. In the sections that follow, I discuss three ways of referring to Range objects in your VBA code: ✦ The Range property of a Worksheet or Range class object ✦ The Cells property of a Worksheet object ✦ The Offset property of a Range object The Range property The Range property returns a Range object. If you consult the online help for the Range property, you’ll learn that this property has two syntaxes: object.Range(cell1) object.Range(cell1, cell2) The Range property applies to two types of objects: a Worksheet object or a Range object. Here, cell1 and cell2 refer to placeholders for terms that Excel will recog- nize as identifying the range (in the first instance) and delineating the range (in the second instance). Following are a few examples of using the Range method. You’ve already seen examples like the following one earlier in the chapter. The instruction that follows simply enters a value into the specified cell. In this case, it puts a 1 into cell A1 on Sheet1 of the active workbook: Worksheets(“Sheet1”).Range(“A1”).Value = 1 The Range property also recognizes defined names in workbooks. Therefore, if a cell is named “Input,” you can use the following statement to enter a value into that named cell: Worksheets(“Sheet1”).Range(“Input”).Value = 1 The example that follows enters the same value into a range of 20 cells on the active sheet. If the active sheet is not a worksheet, this causes an error message: ActiveSheet.Range(“A1:B10”).Value = 2 The next example produces exactly the same result as the preceding example: Range(“A1”, “B10”) = 2 The sheet reference is omitted, however, so the active sheet is assumed. Also, the value property is omitted, so the default property (which is Value, for a Range object) is assumed. This example also uses the second syntax of the Range prop- erty. With this syntax, the first argument is the cell at the top left of the range and the second argument is the cell at the lower right of the range. 4799-2 ch07.F 6/11/01 9:29 AM Page 166 167 Chapter 7 ✦ Introducing Visual Basic for Applications The following example uses Excel’s range intersection operator (a space) to return the intersection of two ranges. In this case, the intersection is a single cell, C6. Therefore, this statement enters 3 into cell C6: Range(“C1:C10 A6:E6”) = 3 And finally, this next example enters the value 4 into five cells, that is, a noncontigu- ous range. The comma serves as the union operator: Range(“A1,A3,A5,A7,A9”) = 4 So far, all the examples have used the Range property on a Worksheet object. As I mentioned, you can also use the Range property on a Range object. This can be rather confusing, but bear with me. Following is an example of using the Range property on a Range object (in this case, the Range object is the active cell). This example treats the Range object as if it were the upper-left cell in the worksheet, and then enters a value of 5 into the cell that would be B2. In other words, the reference returned is relative to the upper-left corner of the Range object. Therefore, the statement that follows enters a value of 5 into the cell directly to the right and one row below the active cell: ActiveCell.Range(“B2”) = 5 I said this is confusing. Fortunately, there is a much clearer way to access a cell rela- tive to a range, called the Offset property. I’ll discuss this property after the next section. The Cells property Another way to reference a range is to use the Cells property. Like the Range prop- erty, you can use the Cells property on Worksheet objects and Range objects. Check the online help, and you’ll see that the Cells property has three syntaxes: object.Cells(rowIndex, columnIndex) object.Cells(rowIndex) object.Cells I’ll give you some examples that demonstrate how to use the Cells property. The first example enters the value 9 into cell 1 on Sheet1. In this case, I’m using the first syntax, which accepts the index number of the row (from 1 to 65536) and the index number of the column (from 1 to 256): Worksheets(“Sheet1”).Cells(1, 1) = 9 Here’s an example that enters the value 7 into cell D3 (that is, row 3, column 4) in the active worksheet: ActiveSheet.Cells(3, 4) = 7 4799-2 ch07.F 6/11/01 9:29 AM Page 167 168 Part III ✦ Understanding Visual Basic for Applications You can also use the Cells property on a Range object. When you do so, the Range object returned by the Cells property is relative to the upper-left cell of the refer- enced Range. Confusing? Probably. An example might help clear this up. The follow- ing instruction enters the value 5 into the active cell. Remember, in this case, the active cell is treated as if it were cell A1 in the worksheet: ActiveCell.Cells(1, 1) = 5 The real advantage of this type of cell referencing will be apparent when I discuss variables and looping (see Chapter 8). In most cases, you will not use actual val- ues for the arguments. Rather, you’ll use variables. To enter a value of 5 into the cell directly below the active cell, you can use the fol- lowing instruction: ActiveCell.Cells(2, 1) = 5 Think of the preceding example as though it said this: “Start with the active cell and consider this cell as cell A1. Return the cell in the second row and the first column.” The second syntax of the Cells method uses a single argument that can range from 1 to 16,777,216. This number is equal to the number of cells in a worksheet (65,536 rows × 256 columns). The cells are numbered starting from A1 and continuing right and then down to the next row. The 256th cell is IV1, the 257th is A2. The next example enters the value 2 into cell H3 (which is the 520th cell in the worksheet) of the active worksheet: ActiveSheet.Cells(520) = 2 To display the value in the last cell in a worksheet (IV65536), use this statement: MsgBox ActiveSheet.Cells(16777216) This syntax can also be used with a Range object. In this case, the cell returned is relative to the Range object referenced. For example, if the Range object is A1:D10 (40 cells), the Cells property can have an argument from 1 to 40 and return one of the cells in the Range object. In the following example, a value of 2000 is entered into cell A2 because A2 is the fifth cell (counting from the top and to the right, then down) in the referenced range: Range(“A1:D10”).Cells(5) = 2000 In the preceding example, the argument for the Cells property is not limited to values between 1 and 40. If the argument exceeds the number of cells in the range, the counting continues as if the range were larger than it actually is. Therefore, a statement like the preceding one could change the value in a cell that’s outside of the range A1:D10. Note Note 4799-2 ch07.F 6/11/01 9:29 AM Page 168 [...]... (negative values); 4.94065645841247E 32 4 to 1.7976 931 3486 232 E308 (positive values) Currency 8 bytes –922 ,33 7,2 03, 685,477.5808 to 922 ,33 7,2 03, 685,477.5807 Decimal 14 bytes +/–79,228,162,514,264 ,33 7,5 93, 5 43, 950 ,33 5 with no decimal point; +/–7.922816251426 433 75 935 439 5 033 5 with 28 places to the right of the decimal Date 8 bytes January 1, 0100 to December 31 , 9999 Object 4 bytes Any object reference String... 32 ,768 to 32 ,767 4799-2 ch08.F 6/11/01 9 :30 AM Page 1 83 Chapter 8 ✦ VBA Programming Fundamentals Data Type Range of Values Long 4 bytes –2,147,4 83, 648 to 2,147,4 83, 647 Single 4 bytes 3. 402823E38 to –1.401298E–45 (for negative values); 1.401298E–45 to 3. 402823E38 (for positive values) Double 8 bytes –1.7976 931 3486 232 E308 to –4.94065645841247E 32 4 (negative values); 4.94065645841247E 32 4 to 1.7976 931 3486 232 E308... AM Page 176 4799-2 ch08.F 6/11/01 9 :30 AM Page 177 8 C H A P T E R VBA Programming Fundamentals I n the preceding chapter, I introduced you to VBA; now it’s time to get better acquainted 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,... The VBA equivalent of Excel s DATE function is DateSerial The following expression (correctly) returns March 1, 1900: DateSerial(1900,2,29) Therefore, Excel s date serial number system does not correspond exactly to VBA s date serial number system These two systems return different values for dates between January 1, 1900 and March 1, 1900 4799-2 ch08.F 6/11/01 9 :30 AM Page 1 93 Chapter 8 ✦ VBA Programming. .. calculation, Excel uses the Double data type, so that’s a good choice for processing numbers in VBA when you don’t want to lose any precision For integer calculations, you can use the Integer type if you’re sure that the values will not 1 83 4799-2 ch08.F 184 6/11/01 9 :30 AM Page 184 Part III ✦ Understanding Visual Basic for Applications exceed 32 ,767 Otherwise, use the Long data type When dealing with Excel. .. F2 to bring up the Object Browser Working with strings Like Excel, VBA can manipulate both numbers and text (strings) There are two types of strings in VBA: 191 4799-2 ch08.F 192 6/11/01 9 :30 AM Page 192 Part III ✦ Understanding Visual Basic for Applications ✦ Fixed-length strings are declared with a specified number of characters The maximum length is 65, 535 characters ✦ Variable-length strings theoretically... Summary In this chapter, I introduced VBA and discussed how VBA compares to other languages I explained that a VBA module contains procedures and that VBA is based on objects, properties, and methods I also explained how to use the macro recorder to translate your actions into VBA code Chapter 8 discusses programming concepts that are necessary to get the most out of VBA ✦ ✦ ✦ 175 4799-2 ch07.F 6/11/01... have said it better myself Much of the work done in VBA involves developing (and debugging) expressions If you know how to create formulas in Excel, you’ll have no trouble creating expressions in VBA With a worksheet formula, Excel displays the result in a cell A VBA expression, on the other hand, can be assigned to a variable or used as a property value VBA uses the equals sign (=) as its assignment operator... problems in dealing with variant data types, try executing this procedure: Sub VariantDemo2() MyVar = “1 23 MyVar = MyVar + MyVar MyVar = “Answer: “ & MyVar MsgBox MyVar End Sub The message box will display: Answer: 1 231 23 This is probably not what you wanted When dealing with variants that contain text string, the + operator performs string concatenation Determining a data type You can use VBA s TypeName... become familiar with VBA, without question, is to simply turn on the macro recorder and record some actions you make in Excel This is a quick way to learn the relevant objects, properties, and methods for a task It’s even better if the VBA module in which the code is being recorded is visible while you’re recording Use the online help system The main source of detailed information about Excel s objects, . into VBA code. Chapter 8 discusses programming concepts that are necessary to get the most out of VBA. ✦✦✦ 4799-2 ch07.F 6/11/01 9:29 AM Page 175 4799-2 ch07.F 6/11/01 9:29 AM Page 176 VBA Programming Fundamentals I n. actions The absolute best way to become familiar with VBA, without question, is to simply turn on the macro recorder and record some actions you make in Excel. This is a quick way to learn the relevant. debugging code. Summary In this chapter, I introduced VBA and discussed how VBA compares to other languages. I explained that a VBA module contains procedures and that VBA is based on objects, properties, and