1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering Excel 2003 Programming with VBA phần 3 pot

61 313 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 61
Dung lượng 1,65 MB

Nội dung

4281book.fm Page 103 Sunday, February 29, 2004 5:12 PM 103 COMMON FILE OPERATIONS SIMPLIFIED sPath = Left(sFullName, nPos - 1) Else 'Invalid sFullName - don't change anything End If End Sub ' Returns the position or index of the first ' character of the filename given a full name ' A full name consists of a path and a filename ' Ex. FileNamePosition("C:\Testing\Test.txt") = 11 Function FileNamePosition(sFullName As String) As Integer Dim bFound As Boolean Dim nPosition As Integer bFound = False nPosition = Len(sFullName) Do While bFound = False ' Make sure we were not dealt a ' zero-length string If nPosition = 0 Then Exit Do ' We are looking for the first "\" ' from the right. If Mid(sFullName, nPosition, 1) = "\" Then bFound = True Else ' Working right to left nPosition = nPosition - 1 End If Loop If bFound = False Then FileNamePosition = 0 Else FileNamePosition = nPosition End If End Function In addition to providing you with a useful way to isolate path- and filename components from a full filename, Listing 5.8 includes one brand new concept, which may not be apparent at first glance—output parameters. Take a look at the declaration of the BreakdownName subroutine. Sub BreakdownName(sFullName As String, _ ByRef sName As String, _ ByRef sPath As String) 4281book.fm Page 104 Sunday, February 29, 2004 5:12 PM 104 CHAPTER 5 EXPLORING THE APPLICATION OBJECT See the ByRef keyword in this declaration? This keyword indicates that when/if the Breakdown- Name function modifies these parameters, the procedure that called BreakdownName will see the changes made to the variables. Listing 5.8 uses a simple procedure to test the BreakdownName procedure. You simply use the Get- SaveAsFilename method to obtain a full filename and pass the filename to the BreakdownName procedure along with two empty variables, sName and sPath. BreakdownName uses the FileNamePosition function to locate the beginning of the filename component. Once you know that, it is simple to break the name down into the path- and filename components using the VBA Left and Right functions. Both Left and Right take a string variable and return the specified number of characters from either the left or the right respectively. In the following screenshots, you can see how I employed the BreakdownName procedure to figure out the path and filename of the file returned from GetSaveAsFilename. Parameters Passed by Reference ByRef means that the parameter is passed by reference. If you do not use the ByRef keyword when you declare parameters, then the parameters are passed by value. You could explicitly specify this by declaring parameters using ByVal. Anyway, rather than get into the details of this, it is probably best to just think of parameters in terms of read/ write. ByVal parameters are read only from the perspective of the calling procedure. The procedure that is called can change the values of the parameters, but the calling procedure never knows about, or sees the changes. By reference or ByRef parameters are read/write from the perspective of the calling procedure. Now when the procedure that is called changes the value of a parameter denoted with ByRef, the calling procedure sees the change. Using ByRef is one way to return or modify more than one value from a function or a subroutine. 4281book.fm Page 105 Sunday, February 29, 2004 5:12 PM 105 INSPECTING YOUR OPERATING ENVIRONMENT Occasionally you’ll have the full filename of a workbook and only be interested in isolating the workbook name only. Listing 5.8 includes a function for just that purpose, called GetShortName, that serves as a shorthand way to use the BreakdownName procedure. Inspecting Your Operating Environment The Application object includes a handful of properties that return information you can use to deter- mine the specifics of the computer your code is running on (see Listing 5.9). You can determine which version of Excel is being used, which operating system is running, as well as memory informa- tion such as how much memory the system has and how much of it is in use. Listing 5.9: System Information Available Using Application Object Properties Sub InspectTheEnvironment() Debug.Print Application.CalculationVersion Debug.Print Application.MemoryFree Debug.Print Application.MemoryUsed Debug.Print Application.MemoryTotal Debug.Print Application.OperatingSystem Debug.Print Application.OrganizationName Debug.Print Application.UserName Debug.Print Application.Version End Sub This code produces the following output on my computer. 114210 1048576 475128 1523704 Windows (32-bit) NT 5.01 Dakota Technology Group, Inc. Steven M. Hansen 11.0 Table 5.2 details some of the system-oriented properties of the Application object. Table 5.2: System-Oriented Properties of the Application Object Property Name Value Returned CalculationVersion Right four digits indicate the version of the calculation engine whereas the digits to the left indicate the major version of Excel. MemoryFree Returns the amount of memory in bytes that Excel is allowed to use, not including memory already in use. 4281book.fm Page 106 Sunday, February 29, 2004 5:12 PM 106 CHAPTER 5 EXPLORING THE APPLICATION OBJECT Table 5.2: System-Oriented Properties of the Application Object (continued) Property Name Value Returned MemoryUsed Returns the amount of memory, in bytes, that Excel is currently using. MemoryTotal Returns the total amount of memory, in bytes, that Excel can use. It includes memory that is already in use. It is the sum of MemoryFree and MemoryUsed. OperatingSystem Returns the name and version of the Operating System. OrganizationName Returns the name of the organization to which the product is registered. UserName Returns or sets the name of the current user. Version Returns the version of Excel that is in use. Two Useful Bonus Members You should be familiar with two more members of the Application object. The first one is the Cut- CopyMode property. This property, though not used nearly as frequently as something like Screen- Updating, is handy in certain situations. Have you noticed that when you use Cut or Copy, Excel shows the range that is being cut or copied using moving dashes around the perimeter? Once in a while you’ll want to do the same thing using VBA and, after you have performed the copy, you don’t want to leave the moving dashes on display (it is not very professional looking). To turn the dashes off, you need to exit CutCopyMode. In the appropriate location in your procedure, insert this line: Application.CutCopyMode = False The second member that is useful to know is the InputBox method. InputBox allows you to cap- ture simple input from your user. The syntax of InputBox is as follows: InputBox(prompt, [title], [default], [xpos], _ [ypos], [helpfile], [context]) The parameters to InputBox are as follows. Prompt This is the only required parameter. It is the text that is displayed that indicates what the user should enter as input. Title This is an optional parameter. Any text you supply will be displayed in the title bar of the input box. If omitted, the application name is used. 4281book.fm Page 107 Sunday, February 29, 2004 5:12 PM 107 SUMMARY Default An optional parameter that, if supplied, is used as the default value in the input area of the input box. Xpos An optional parameter that specifies the distance between the left edge of the input box and the left edge of the window. If omitted the input box is horizontally centered. Ypos An optional parameter that specifies the distance between the top edge of the input box and the top edge of the window. If omitted the input box is about 1 / 3 of the way down the screen. Helpfile An optional parameter that specifies the help file used to provide context-sensitive help. If this parameter is provided, you must also provide a context parameter. Context An optional parameter that specifies the help context number of the appropriate help topic. If this parameter is specified, you must also provide the Helpfile parameter. The following code snippet provides an example of the usage of the InputBox function. Sub SimpleInputBox() Dim vInput As Variant vInput = InputBox("What is your name?", _ "Introduction", Application.UserName) MsgBox "Hello, " & vInput & ". Nice to meet you.", _ vbOKOnly, "Introduction" End Sub The following screenshot shows an example of this simple procedure. Summary The Application object contains many members. As the root object of the Excel object model, many of the members are Excel objects that I’ll cover later in the book. However, many members are specific to the Application object. This chapter looked at the most commonly used Application properties and methods that pertain to working with the display, returning convenient Excel objects, handling common file operations, and gathering information about the system environment. Two properties of the Application object control aspects of the display that are very common and nearly indispensable when you are trying to develop a polished, professional-looking Excel applica- tion. The ScreenUpdating property allows you to control when the screen is updated so that your application runs faster and doesn’t flash spasmodically as it runs. The StatusBar property provides an easy, subtle, and nonintrusive way to display status information and messages to the user. The Application object contains a number of properties that return Excel objects that represent objects currently in use such as ActiveCell, ActiveSheet, Selection, and ThisWorkbook. You should only use these items to refer to active items when you really need the active item. If you use the Activate 4281book.fm Page 108 Sunday, February 29, 2004 5:12 PM 108 CHAPTER 5 EXPLORING THE APPLICATION OBJECT method before using one of these properties, you are making your programming chores more difficult and error prone, and as a result, the performance of your application suffers. In coming chapters, you’ll see that you don’t need to activate objects to work with them. The methods GetOpenFilename and GetSaveAsFilename provide quick access to the familiar Open and Save As dialog boxes common to nearly all Windows applications. You’ll use these meth- ods often, and because of this, it may make sense to wrap these methods into your own procedure that performs other related functionality, such as checking the validity of the result of these methods. In the coming chapters, I’ll tackle the Workbook object and the Worksheet object. In Chapter 6, I’ll dive deeper into the topic of opening and saving workbooks using the functionality of GetOpen- Filename and GetSaveAsFilename. Though you can use these methods with one call, you risk run- time errors if you don’t incorporate some defensive programming tactics in your code. In addition, I’ll cover other common properties and methods associated with the Workbook object. 4281book.fm Page 109 Sunday, February 29, 2004 5:12 PM Chapter 6 Working with the Workbook Object The Workbook object represents a single workbook. Though the Workbook object has many properties and methods, you’ll use only a handful on a regular basis. In this chapter, you’ll examine these common properties and methods along with a few events associated with the Workbook object. Many objects have a set of actions to which they’ve been designed to respond. The actions that an object recognizes are known as events. You can write procedures that execute when an object recog- nizes that a given event has occurred. For example, the Workbook object has an Open event; when- ever a workbook is opened, VBA looks for any code associated with the Open event and executes it. You’ll also look at the Workbooks collection object, known as the Workbooks object. The Workbooks object represents all of the Workbook objects that are open in Excel. Finally, I’ll put together all of the concepts you’ve learned so far to create a set of procedures that you’ll find useful for any process in which you need to apply processing to one or more workbooks. Walk before You Run: Opening and Closing Workbooks Before you can do anything with a Workbook object, you need to have a Workbook object on which to work. Because this is a VBA book, you might as well open and close your workbooks program- matically. In order to open and close workbooks, you need to use the Workbooks object. It represents all of the open workbooks in Excel and has methods that can open a new workbook, open an existing workbook, or close a workbook. Like all collection objects, the Workbooks object has an Item property that you can use to access a spe- cific item in the collection and a Count property that returns the number of objects in the collection. The easiest way to obtain a workbook to play with programmatically is to just add a new work- book. You can achieve this using the Add method. The syntax for the Add method is as follows: Workbooks.Add (template) The template parameter is optional and can be a string specifying the name of an existing workbook that will be used as a template. Alternatively, template can be a constant that specifies that a new workbook should be created with one worksheet of a specific type. You can choose from four types: 4281book.fm Page 110 Sunday, February 29, 2004 5:12 PM 110 CHAPTER 6 WORKING WITH THE WORKBOOK OBJECT xlWBAChart, xlWBAExcel4IntlMacroSheet, xlWBAExcel4MacroSheet, and xlWBATWorksheet. These represent a chart sheet, two flavors of macro sheets, and a standard worksheet, respectively. Finally, if you don’t specify a template, Excel just creates an empty, standard workbook. If you want to open an existing workbook, use the Open method of the Workbooks object. The syntax of Open looks rather daunting because there are so many parameters (16 of them!). Thank- fully, all of them except for the first one are optional. Workbooks.Open(Filename, [UpdateLinks], [ReadOnly], _ [Format], [Password], [WriteResPassword], _ [IgnoreReadOnlyRecommended], [Origin], [Delimiter], _ [Editable], [Notify], [Converter], [AddToMru], [Local], _ [CorruptLoad]) Because I’d like this book to be packed with useful and practical content rather than replicate Excel’s help files, I’ll not go into the details of every parameter here. Most of the time, you’ll use the Open method with its only required parameter—the FileName. Occasionally, I’ll also use the UpdateLinks and ReadOnly parameters. You can set ReadOnly to true to open the workbook in read-only mode. By default this parameter is false (read-write mode). If the workbook you’re opening contains links, you may want to use the UpdateLinks parameter with one of the values shown in Table 6.1. Table 6.1: Valid UpdateLinks Values Value UpdateLinks Behavior 0 Links are not updated. 1 External links are updated but not remote links. 2 Remote links are updated but not external links. 3 Both remote and external links are updated. You can close workbooks using the Close method of either the Workbooks object or the Workbook object. The difference is that the Close method on the Workbooks object closes all open workbooks whereas the Close method on the Workbook object closes just that workbook. Listing 6.1 incorporates many of the skills you’ve learned so far into a set of procedures that you can use to process a batch of workbooks. This is a fairly lengthy listing because it is a fairly robust set of procedures that you can use in real-life situations. Listing 6.1: A Robust, Batch Workbook Processing Framework Sub ProcessFileBatch() Dim nIndex As Integer Dim vFiles As Variant Dim wb As Workbook Dim bAlreadyOpen As Boolean On Error GoTo ErrHandler 4281book.fm Page 111 Sunday, February 29, 2004 5:12 PM 111 WALK BEFORE YOU RUN: OPENING AND CLOSING WORKBOOKS ' Get a batch of Excel files vFiles = GetExcelFiles("Select Workbooks for Processing") ' Make sure the dialog wasn't cancelled - in which case ' vFiles would equal False and therefore wouldn't be an array. If Not IsArray(vFiles) Then Debug.Print "No files selected." Exit Sub End If Application.ScreenUpdating = False ' OK - loop through the filenames For nIndex = 1 To UBound(vFiles) If IsWorkbookOpen(CStr(vFiles(nIndex))) Then Set wb = Workbooks(GetShortName(CStr(vFiles(nIndex)))) Debug.Print "Workbook already open: " & wb.Name bAlreadyOpen = True Else Set wb = Workbooks.Open(CStr(vFiles(nIndex)), False) Debug.Print "Opened workbook: " & wb.Name bAlreadyOpen = False End If Application.StatusBar = "Processing workbook: " & wb.Name ' Code to process the file goes here Debug.Print "If we wanted to do something to the " & _ "workbook, we would do it here." ' Close workbook unless it was already open If Not bAlreadyOpen Then Debug.Print "Closing workbook: " & wb.Name wb.Close True End If Next nIndex ' Clean up Set wb = Nothing ErrHandler: Application.StatusBar = False Application.ScreenUpdating = True End Sub [...]... Case xlDBF3: sFormat = "DBF 3" Case xlDBF4: sFormat = "DBF 4" Case xlDIF: sFormat = "DIF" Case xlExcel2: sFormat = "Excel 2" Case xlExcel2FarEast: sFormat = "Excel 2 Far East" Case xlExcel3: sFormat = "Excel 3" Case xlExcel4: sFormat = "Excel 4" Case xlExcel4Workbook: sFormat = "Excel 4 Workbook" Case xlExcel5: sFormat = "Excel 5" Case xlExcel7: sFormat = "Excel 7" Case xlExcel9795: sFormat = "Excel 97/95"... xlWebArchive: sFormat = "Web Archive" Case xlWJ2WD1: sFormat = "WJ2WD1" Case xlWJ3: sFormat = "WJ3" Case xlWJ3FJ3: sFormat = "WJ3FJ3" RESPOND TO USER ACTIONS WITH EVENTS Case xlWK1: sFormat = "WK1" Case xlWK1ALL: sFormat = "WK1ALL" Case xlWK1FMT: sFormat = "WK1FMT" Case xlWK3: sFormat = "WK3" Case xlWK3FM3: sFormat = "WK3FM3" Case xlWK4: sFormat = "WK4" Case xlWKS: sFormat = "WKS" Case xlWorkbookNormal:... substantially with the number of events that you respond to That said, the events associated with the Workbook object are generally fairly easy to work with So what kind of events would be associated with a workbook? Well, think about the kinds of things that happen to them—they get opened, closed, saved, activated, and deactivated Table 6 .3 presents a complete list of the events associated with the Workbook...112 CHAPTER 6 WORKING WITH THE WORKBOOK OBJECT Procedural Programming Procedural programming is a programming paradigm in which a program is constructed of small procedures that are linked together to perform a given task One school of thought regarding procedural programming is that procedures have one and only one exit point In Listing 6.1,... case a Workbook object) within a collection by specifying its name within parentheses Remember the part about the On Error Resume Next statement being so critical to this function? Here is why If you recall, the Workbooks object is the collection of all open workbooks If you attempt 115 116 CHAPTER 6 WORKING WITH THE WORKBOOK OBJECT Scrutinizing Strings with InStr and StrComp VBA has a number of built-in... you need to come to grips with the different ways to work with individual items within a collection As I mentioned earlier in the chapter, all collection objects have an Item property that you can use to refer to individual items within the collection For the vast majority of collections, the Item prop­ erty is the default property This means that you can access the property without specifying it The... its code name In the Project Explorer window shown next, you can see that after you set the code name, the worksheet appears under Microsoft Excel Objects using its code name with its real name, or the name the user sees, in parentheses 135 136 CHAPTER 7 WINNING WITH WORKSHEETS You can programmatically distinguish between the code name and the real name using the prop­ erties CodeName and Name respectively... business is to construct a loop that will loop through every filename returned from the GetExcelFiles function As we discussed in the last chapter, the GetOpenFilename method used within the GetExcelFiles function returns a one-based array rather than a zero-based array, which is the conventional way to work with arrays Inside the loop, you need to assign the workbook referred to by the filename to... significant difference exists between using this func­ tion with a short name versus a full name When you use this function with a short name, you aren’t considering the possibility that a workbook with the same name exists in multiple folders This is fine in situations in which you want to check whether it is safe to open a file (you can’t have two files open with the same name even if they are stored in separate... first exposure to working with events in VBA Events allow you to create powerful applications that are aware of and respond to various actions that occur due to pro­ grammatic and/or end user activities Something about events excites me I’m not sure if it is the extra dose of control that events provide or what, but working with events definitely adds to the excitement of programming Some of that excitement . Sunday, February 29, 2004 5:12 PM 112 CHAPTER 6 WORKING WITH THE WORKBOOK OBJECT Procedural Programming Procedural programming is a programming paradigm in which a program is constructed of. 2004 5:12 PM 116 CHAPTER 6 WORKING WITH THE WORKBOOK OBJECT Scrutinizing Strings with InStr and StrComp VBA has a number of built-in functions for working with strings. InStr and StrComp are. methods with one call, you risk run- time errors if you don’t incorporate some defensive programming tactics in your code. In addition, I’ll cover other common properties and methods associated with

Ngày đăng: 13/08/2014, 15:20

TỪ KHÓA LIÊN QUAN