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

Mastering Excel 2003 Programming with VBA phần 10 docx

57 338 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 57
Dung lượng 1,37 MB

Nội dung

4281book.fm Page 529 Monday, March 1, 2004 1:19 AM Chapter 22 Application Deployment Strategies One thing that will become evident to you shortly after you release your first Excel application is that even though you’ve finished developing, your work is far from complete. You have users to support, bugs to fix (though many strive for it, nobody’s perfect), and new features to add. You know the saying “If you fail to plan, you plan to fail”? After just a couple of releases, if you don’t plan your application releases and upgrades, you may find your state of affairs bordering on chaos—especially if you’ve got lots of users (dozens to hundreds). In order to manage the product distribution and release cycle, you can employ numerous strategies, from rudimentary to comprehensive fail-proof release management systems. This chapter introduces you to a few strategies you can use to manage application distribution. Another issue related to application deployment is determining what form your application will be in when you distribute it. You can choose from distributing your application as a standard work- book, a template, or an add-in. I’ll present the pros and cons of each form so that you can make an informed choice. The choice of an application deployment strategy is a decision that is best made near the beginning of the development process because the decisions you make during the development process can be impacted depending on the distribution form of your application. Choose the Form Do you remember the movie Ghostbusters (1984)? The Ghostbusters are fighting the evil demon Gozer (aka Gozer the Gozerian, Gozer the Destructor, Voguss Zildrohar, The Traveller). Just prior to assuming a physical presence, Gozer asks the Ghostbusters to choose the form of their destroyer. As they all stop to ponder their decision, Gozer appears as a giant Stay Puft marshmallow man. Sure enough, Stantz (played by Dan Akroyd) made the mental decision without the input of his colleagues. His reasoning? “I tried to think of the most harmless thing… something that could never destroy us… something I loved from my childhood.” As it turned out, the Ghostbusters eventually destroyed Gozer before Gozer could bring about worldwide destruction. When it comes to choosing the form of distribution for your application, it’s safe to say that your choice won’t have worldwide life and death consequences. There are consequences however. 4281book.fm Page 530 Monday, March 1, 2004 1:19 AM 530 CHAPTER 22 APPLICATION DEPLOYMENT STRATEGIES I Like Vanilla The most common form an Excel application takes is as a plain vanilla workbook. This next sentence is very important so pay attention. In order to create an application that assumes this form, you must save your workbook (File � Save). OK, I’m playing a little bit. Telling you how to save a workbook is kind of like telling you how to breathe. The biggest benefit of using a standard Excel workbook is that you don’t need to worry about installing it before using it. You can e-mail the workbook, place it in a shared network folder, or save it to portable media. As long as your users can open the workbook, they can use the functionality it supplies, provided it passes the Microsoft Office security checks. That said, it is not uncommon for a handful of your users to experience issues related to either a faulty Office or Excel installation. Well, it’s not necessarily that the original Excel installation was faulty— rather something probably happened to the computer after the fact that caused an incompatibility or removed critical system files. If your application works for the vast majority of your users and doesn’t work at all for a tiny minority, your leading suspect should be the details associated with these indi- vidual computers. If you quiz these users, usually you’ll find out that they recently had software pack- age X (substitute any number of software programs here) installed or removed, and that ever since, Excel has exhibited unpredictable behavior. If my application doesn’t work after I verify that all of the software requirements it needs have been met, I’ll devise a trivial procedure that should work on every computer to test the offending computers. If the trivial procedure fails as well, I’ll have the users or their IT support department reinstall Microsoft Office and all applicable service packs. Most of the time this solves the problem. Repeat Your Success with Templates Another form your solution can assume is a template. Templates are useful for applications that pro- vide functionality that is used to help automate repeated processes or procedures. For example, maybe your firm has a standard capital spending approval process that requires finan- cial justification as part of the approval process. You could develop a template that facilitates this pro- cess by assisting users with the data input process, producing reports, and submitting workbook data for approval. Though you could add functionality to a normal workbook solution to make it act like a template, why not just save the original as a template and get all of the template functionality for free? (A coun- terpoint is provided in two paragraphs.) When your users need to create a new capital spending approval request, all they need to do is select File � New, choose the On My Computer link under- neath Templates in the task pane, and then select the capital spending template. Templates also allow you to develop worksheet-based solutions. That is, you can develop a work- sheet that performs some specific task and then save it as a worksheet template. Then you can insert the worksheet template as a new worksheet in any workbook that requires the functionality provided by the worksheet. The minor disadvantage of a template is that it requires a little more knowledge to use than a stan- dard workbook. Occasionally I find it difficult to remember that some people don’t know how to add two cells together in Excel (probably a larger percentage of users than you think). The fact is, if your solution is being distributed to a large number of users, you’ll need to create a utility to install the tem- plate to the proper template directory (or provide documentation on how to do this manually). Addi- tionally, you will also need to train people on how to create a workbook based on a template. How 4281book.fm Page 531 Monday, March 1, 2004 1:19 AM 531 CHOOSE THE FORM you deliver this training (proactive documentation, proactive communication/training, or reactive communication) is up to you, but you will end up delivering it. The alternative to using a template is to distribute a standard workbook that contains a user inter- face element that says something like “Create New <your solution>”. When you click the Create New button, or whatever, all your code needs to do is provide a way for the user to name the new workbook and select a location to save it (you can use the GetSaveAsFilename method) and then save the solution workbook using the new name and location. Whenever the user needs to create a new document, they open up the original file you distributed and click the Create New button. Perhaps an example of the different alternatives for delivering template functionality is in order at this point. I’d like to demonstrate three things: how to create a template, how to create a workbook that acts like a template, and how to create a worksheet template. As an example of how to create a template and how to create a workbook that acts like a template, I’ve taken the Setting and Settings classes along with the Settings worksheet from Chapter 12 and placed them into a workbook with two empty worksheets. Because I use the settings functionality in nearly every Excel project, my goal is to create a template that I can use to kick off each Excel appli- cation I build. Though this example just adds the settings functionality to this workbook, you may want to add other components that you find yourself using in nearly every project. Figure 22.1 shows an example of the Excel Project workbook that I’ll turn into a template. Creating a template given an existing workbook is easy as the following steps illustrate: 1. Select File � Save As. 2. Change Save As Type to Template (*.xlt). 3. In order to have the template appear in the list of templates displayed by the Templates dialog box, you should save the file to the Templates folder, which is located by default at C:\Documents and Settings\username\Application Data\Microsoft\Templates. I saved mine with the name Excel Project. Figure 22.1 This otherwise empty workbook contains the compo- nents necessary to implement set- tings as covered in Chapter 12. 4281book.fm Page 532 Monday, March 1, 2004 1:19 AM 532 CHAPTER 22 APPLICATION DEPLOYMENT STRATEGIES Tip You can determine the path to the Templates folder programmatically using Application.TemplatesPath. Piece of cake! To use the template, follow these steps: 1. Select File � New 2. Choose the On My Computer option underneath the Templates section in the task pane. 3. Double-click the Excel Project template. Warning The most common error made by users trying to use a template is that they open the template itself (by open- ing a template workbook directly) rather than creating a new workbook based on a copy of the template. As you might infer from the warning about opening templates directly being the most common error, in order to modify a template, you need to open the template up directly by selecting File � Open and then selecting the template file. In order to create a pseudo-template (a workbook that imitates Template functionality) you need to use some VBA. Listing 22.1 presents an example of code you can use to implement pseudo- template functionality. If some of the procedures in this listing look familiar, it’s because you saw a few of them in Chapter 6 when you learned about the Workbook object. Listing 22.1: Implementing Pseudo-Template Functionality Option Explicit ' Create new workbook based on this workbook Sub SimplePsuedoTemplate() Dim wb As Workbook Dim sName As String Dim sDefault As String Dim sFilter As String ' Default file name sDefault = GetDefaultName ' Filter for GetSaveAsFilename method sFilter = "Microsoft Office Excel Workbook (*.xls), *.xls" ' Ask user where to save new file sName = Application.GetSaveAsFilename(sDefault, sFilter) ' False means user clicked cancel or dismissed dialog box ' without making a choice If sName <> "False" Then ' See if a file already exists at the selected location If FileExists(sName) Then ' There IS an existing file - see if the user ' wants to overwrite it. 4281book.fm Page 533 Monday, March 1, 2004 1:19 AM 533 CHOOSE THE FORM If OkToOverwrite(sName) Then ' Turn off alerts so Excel doesn't bug ' the user about the existing file Application.DisplayAlerts = False ThisWorkbook.SaveAs sName ' Turn alerts back on Application.DisplayAlerts = True End If Else ' There IS NOT an existing file so ' go ahead and save thisworkbook as sName ThisWorkbook.SaveAs sName End If End If Set wb = Nothing End Sub ' Generates a default file name Function GetDefaultName() As String Dim bGotName As Boolean Dim sName As String Dim nIndex As Integer nIndex = 1 bGotName = False Do sName = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4) & _ CStr(nIndex) If IsWorkbookOpen(sName & ".xls") Then nIndex = nIndex + 1 Else bGotName = True End If Loop Until bGotName GetDefaultName = sName & ".xls" End Function ' See if a given workbook is open or not Function IsWorkbookOpen(sWorkbookName As String) As Boolean Dim wb As Workbook IsWorkbookOpen = False For Each wb In Workbooks If StrComp(sWorkbookName, wb.Name, vbTextCompare) = 0 Then IsWorkbookOpen = True Exit For 4281book.fm Page 534 Monday, March 1, 2004 1:19 AM 534 CHAPTER 22 APPLICATION DEPLOYMENT STRATEGIES End If Next Set wb = Nothing End Function ' Ask if it's ok to overwrite a file Function OkToOverwrite(sFullName As String) As Boolean Dim sMsg As String Dim nButtons As Long Dim nResponse As Long Dim bOverwrite As Boolean bOverwrite = False sMsg = sFullName & " already exists. Do you want to overwrite it?" nButtons = vbYesNoCancel + vbExclamation + vbDefaultButton2 nResponse = MsgBox(sMsg, nButtons, "Overwrite File?") If nResponse = vbYes Then bOverwrite = True End If OkToOverwrite = bOverwrite End Function ' See if a file exists or not Function FileExists(sFullName As String) As Boolean Dim bExists As Boolean Dim nLength As Integer nLength = Len(Dir(sFullName)) If nLength > 0 Then bExists = True Else bExists = False End If FileExists = bExists End Function Basically all this listing does is save the workbook using a different name. In order to be a little more convenient, the listing does things like generate a default filename, prompt the user for a file- name and storage location, check to see if a file with the same name already exists, and if so, ask if it’s 4281book.fm Page 535 Monday, March 1, 2004 1:19 AM 535 CHOOSE THE FORM OK to overwrite the existing file. Of course, to make things even more user friendly, if this were a pro- duction application, you would want to add a user interface element (menu item, command button, etc.) that calls the SimplePsuedoTemplate procedure for the user. One of the advantages of using a pseudo-template in place of a real template is that you can build initialization code into the process that creates the new workbook. For example, it would be easy to modify Listing 21.1 to prompt for the initial settings for the project such as the App Name, App Ver- sion, and App Date. Using Worksheet Templates Though many people are not aware of it or don’t take advantage of it, you can also create a worksheet template. Worksheet templates allow you to insert worksheets exhibiting predefined formatting or functionality into a workbook. Using the Settings functionality as an example, let me explain one way that you could put a worksheet template to good use—by creating a Settings worksheet template. Then, if you wanted to add Settings functionality to a particular workbook, you could add a new Set- tings worksheet (based on the Settings template you’ll create shortly) and import the two classes that provide setting functionality (the Settings and Setting classes). Creating a worksheet template is very similar to creating a workbook template. The main differ- ence is that you need to be sure to limit the worksheets in the workbook to just those that you want to appear when you insert them into a workbook based on the template. To create a worksheet tem- plate based on the Settings worksheet, follow these steps: 1. Create a workbook that contains just one worksheet (the Settings worksheet). 2. Select File � Save As. 3. Change Save As Type to Template (*.xlt). 4. In order to have the template appear in the list of templates displayed by the Templates dialog box, you should save the file to the Templates folder, which is located by default at C:\Doc- uments and Settings\username\Application Data\Microsoft\Templates. I saved mine with the name Settings. Using a worksheet template is easy enough if you know where to look. The only way I know to insert a worksheet template is to right-click the worksheet tab that I want to insert a worksheet in front of and select Insert. This displays the Insert dialog box shown in Figure 22.2. Then all I need to do is select the desired template and click OK. Note If you select a template containing more than one worksheet, Excel will insert a worksheet for every worksheet found in the template. Blend in with Add-Ins Add-ins are useful when you have functionality that is not workbook specific—for example, you could develop a bunch of user-defined functions and distribute them as an add-in. This works won- derfully, because generally you’ll want to use the functions from within many different workbooks. 4281book.fm Page 536 Monday, March 1, 2004 1:19 AM 536 CHAPTER 22 APPLICATION DEPLOYMENT STRATEGIES Figure 22.2 Inserting a work- sheet based on a template is as easy as double-clicking the appropriate template. Another benefit of an add-in is that its structure is not visible to the user. A workbook (and there- fore a template) must have at least one visible worksheet. This rule does not apply to an add-in. Though you can protect a workbook so that it is difficult, at best, to modify, add-ins cannot be mod- ified in anyway by a user. The only way to modify an add-in is to modify the workbook with which the add-in was created. As an example, I’ve created a simple add-in that contains two user-defined functions: one function that prints out the connection details of the query table associated with a given range and another that lists all of the very hidden worksheets in the active workbook. To test this out, create a new workbook and enter the code from Listing 22.2. Listing 22.2:Useful Add-In Functions Option Explicit ' Lists the connection details of the query table that ' intersects with the QueryTableCell parameter Function ViewQueryTableConnection(QueryTableCell As Range) As String Dim sResult As String On Error Resume Next sResult = "" If QueryTableCell.QueryTable Is Nothing Then sResult = "No query table." Else sResult = QueryTableCell.QueryTable.Connection End If 4281book.fm Page 537 Monday, March 1, 2004 1:19 AM 537 CHOOSE THE FORM ViewQueryTableConnection = sResult End Function ' Lists any worksheets in the active workbook ' that are very hidden Function ListVeryHiddenSheets(AnyCell As Range) As String Dim ws As Worksheet Dim sResult As String On Error Resume Next sResult = "" For Each ws In AnyCell.Parent.Parent.Worksheets If ws.Visible = xlSheetVeryHidden Then sResult = sResult & ws.Name & ", " End If Next ' Strip off trailing ", " if needed If Len(sResult) > 2 Then sResult = Left(sResult, Len(sResult) - 2) Else sResult = "There are no very hidden worksheets." End If Set ws = Nothing ListVeryHiddenSheets = sResult End Function The ViewQueryTableConnection function is useful to view the connection details associated with a query table. When you use Microsoft Query to bring data from a database into a worksheet, the data is displayed in a range of cells called a query table. If you use Microsoft Query frequently, occasionally you will need to figure out what database a particular query table is associated with. You can use ViewQueryTableConnection to display this information. To use ViewQueryTableConnection, all you need to do is pass it a reference to a cell that is part of the query table. Figure 22.3 shows an exam- ple that uses ViewQueryTableConnection. I added the ListVeryHiddenSheets function as another example in case you wanted to test an add- in without creating a query table. Pass this function as a reference to any cell in the workbook you want to inspect and it will return a comma-delimited list of the names of any very hidden worksheets in the workbook. To make an add-in, all you need to do is save a workbook as one. Prior to saving the workbook, you may want to lock the VBA project so that people can’t view the code that implements your add-in. For this example, perform the following actions: 4281book.fm Page 538 Monday, March 1, 2004 1:19 AM 538 CHAPTER 22 APPLICATION DEPLOYMENT STRATEGIES Figure 22.3 Viewing the details associated with a query table 1. Select the VBA project associated with Listing 22.2 in the Project Explorer window. 2. Right-click and select VBAProject Properties. 3. Click the Protection tab. 4. Check Lock project for viewing and provide a password (I used “password”). 5. Save the workbook as Simple Add-in.xls. 6. Now you’re ready to make the add-in. Save the workbook as Simple Add-in.xla. You can do this by changing the file type to Microsoft Office Excel Add-in (*.xla). When you do this, Excel will automatically select the AddIns folder associated with your user ID. On my computer, the default AddIn folder is C:\Documents and Settings\shansen\Application Data\Microsoft\AddIns. To test the add-in, you need to load it into memory. In addition, the first time you use an add- in, you need to instruct Excel where to find it. To test the Simple Add-in, follow these steps. 1. Select Tools � Add-Ins from the Excel menu. 2. The first time you use an Add-In you need to add it to the list of Add-Ins by clicking Browse. 3. Locate the Add-In file you created in step 6 of the previous set of instructions. Select the Add- In and click OK to add the add-in to the list of Add-Ins. [...]... 374–380, 374–375 Anchor parameter, 431 And operator in database filters, 359 in VBA, 49 apostrophes (') for comments, 38 for text data, 324 AppendOnImport property, 396 Application object, 87–88 for copying, 106 display-oriented features for, 88–95, 90 for file operations, 96 105 for input, 106 107 , 106 for operating environment, 105 106 properties in, 95–96 applications, 4–5 ApplyFormatCode procedure, 219–220,... BordersAround method, 214, 216–217 BoundColumn property, 428 branching with If Then, 53–57 with Select Case, 57–59 Break mode Auto Data Tips in, 22 for debugging, 69–72, 70–72 entering, 72 exiting, 67 for run-time errors, 79 Break When Value Is True option, 77 BreakdownName procedure, 102 103 , 105 , 115, 553 breaking down filenames, 101 105 , 104 BreakLink method, 118 Breakpoints, 72, 82 bubble sort algorithm,... Windows Explorer at the Start folder associated with your user ID 2 Locate and expand the Templates folder associated with your user ID By default, the relative path to this starting with the documents folder associated with your login (i.e C:\Documents and Settings\shansen) is Application Data\Microsoft\Templates Figure 22.4 shows an example of this 3 With the Templates folder selected, choose File... 1 1 No 0.3.3 2 2 No 1.0.0 3 2 Yes 1.0.1 Step 2: Prepare an Excel Project The next thing to do is to put the handy Excel Project template you created earlier in the chapter to good use and create an empty Excel Project workbook If you recall, the Excel Project template creates a workbook that contains the Setting and Settings classes along with a Settings worksheet You still have a few details to take... Inconvenience notwithstanding, start­ ing over may be expensive to boot For example, if you’ve distributed an application to 500 users and each user has 2 hours of time invested in customizing, entering data into, or otherwise working with the application in a way that a new version will undo, that’s 100 0 hours of work that would be thrown out All of a sudden, the extra work associated with a solution... IsWorkbookOpen = False End If End If End Function ' Presents user with a GetOpenFileName dialog that allows ' multiple file selection ' Returns an array of filenames Function GetExcelFiles(sTitle As String) As Variant Dim sFilter As String MANAGING CHANGE Dim bMultiSelect As Boolean sFilter = "Workbooks (*.xls), *.xls" bMultiSelect = True GetExcelFiles = Application.GetOpenFilename(FileFilter:=sFilter,... associated with upgrading templates by putting a master template on your network and having users install shortcuts to the master copy in their template directories Add-ins are useful in situations in which you need to develop functionality that needs to be accessed from all workbooks An add-in essentially extends the functionality of Excel Though you construct an add-in using a normal Excel workbook,... current) Once you have the data associated with the current version from the database, you need to figure out what version is indicated in the workbook To do this, I used the GetVersionID procedure to query the database for the VersionID associated with the ver­ sion indicated in the workbook GetVersionID returns –1 if it cannot find the VersionID associated with a given version Anyway, CheckVersion... as current, the implementation will use the one that was added most recently A better way to do this may be to have a separate table with just one record and one field that contains the VersionID of the current version Anyway, I digress, for this is a book about Excel VBA, not about database design While you still have the database open, you could go ahead and enter a few test versions into the VersionInfo... command, 424–427, 425, 427 in user interface, 413–414, 414–415 ButtonText parameter in GetOpenFilename, 96 in GetSaveAsFilename, 101 ByRef keyword, 104 Byte data type, 42 C Calculate event, 148 calculated fields, 357, 358 calculations in workbook design, 295 CalculationVersion property, 105 Call Stack window, 79, 79 call stacks, 78–79, 79 Call statement, 38 CallBadProcedure macro, 67 Cancel buttons, 468 Cancel . Viewing the details associated with a query table 1. Select the VBA project associated with Listing 22.2 in the Project Explorer window. 2. Right-click and select VBAProject Properties. 3 associated with your user ID. 2. Locate and expand the Templates folder associated with your user ID. By default, the relative path to this starting with the documents folder associated with your. Excel Project The next thing to do is to put the handy Excel Project template you created earlier in the chapter to good use and create an empty Excel Project workbook. If you recall, the Excel

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

TỪ KHÓA LIÊN QUAN