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

Mastering Excel 2003 Programming with VBA phần 6 ppt

61 358 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 2,52 MB

Nội dung

4281book.fm Page 286 Sunday, February 29, 2004 5:12 PM 286 CHAPTER 13 EXCEL DEVELOPMENT BEST PRACTICES Finally, chances are that the version of Microsoft Windows you use is geared toward supporting multiple users on the same computer. In order to support this capability, each user’s files should be kept separate from other users’ files. In order to play by the rules, your application shouldn’t force users to store user-specific information in a “common” file location. For example, it shouldn’t force everyone to store their files in a folder named C:\Excel Application\Reports . Tips for Creating Portable Applications So what can you do to create portable applications? Here are a few things to keep in mind when cod- ing for workbook portability. ◆ Use configurable relative paths to any application-specific folders. It is easy to allow the user to choose the names of these folders. ◆ If you do use application-specific folders, check for the presence of these folders in the Work- book Open event. If they don’t exist, offer to create them. ◆ Always validate file locations and check to make sure files exist before using them. ◆ Avoid using registry keys or INI files. ◆ If you can’t create a portable application, provide a way for users to export key sections of the workbook (such as reports) to code- and link-free workbooks. Test the Water before Jumping In I’ve analyzed several procedures related to validating object names before setting a reference to an object by name. Remember, always check worksheet names, range names, filenames, Setting names (if you’re using the Settings class from the last chapter), and any other object name before you explicitly set an object reference using the name. One of the differences between developing in VBA with Excel as a host and developing a stand- alone application with a traditional programming language is that when you develop in Excel, you don’t have 100-percent control over how a user interacts with your application; therefore you need to be wary of things that the end user could do that would affect whether your program operates properly. When you develop a stand-alone application using Visual Basic or some other program- ming language, you have total control over everything. The drawback of having all of the control is that you have to write a lot more code. Because validating objects is such a common task, I place all of my validation procedures together in a module that I include in every project I work on. This module contains most of the generic pro- cedures presented in this book such as WorksheetExists, RangeNameExists, and WorkbookExists. Remember Your Math Think back to your school days. Remember algebra? Trying hard to forget? One of the concepts taught in my algebra classes was a concept called factoring. Factoring is the process of taking a long equation and rearranging it so that it can’t be rearranged in a more concise way. For example, the poly- nomial 2xy + 2xy can be factored to 4xy. 4281book.fm Page 287 Sunday, February 29, 2004 5:12 PM 287 THINK LIKE AN ENVIRONMENTALIST You should approach your VBA modules with the same mindset. How can my procedures be rear- ranged so that there is no duplication of code? The best way to achieve this is to create small, focused procedures that each perform only one dedicated task. There are many benefits to factoring your code. In my opinion, the three most important benefits of creating factored code are increased reuse opportunity, reduced complexity, and improved tuning ability. There are two different levels of reuse: the first level is reuse within the same module or project and the second level is reuse within other projects. An exciting thing happens with factored code— you experience a wonderful snowball effect. You’ll find that as soon as you get a critical mass of small, focused procedures, lights will go on that wouldn’t have been activated if your code consisted of long, complicated routines. You’ll see new ways to combine these small procedures to provide new levels of functionality, without incurring a significant development burden. The second level of reuse is significant because you can dramatically reduce the development time of future projects by collecting all of those useful, common routines and using them together as a springboard to jumpstart your next project. This book has presented a decent number of common Excel routines that can seed your collection. For example, the WorksheetExists function that I’ve mentioned numerous times in this book is something that I need to use in nearly every project. Another benefit of factored routines is that they reduce complexity and are therefore much easier to maintain. The benefit of this is that it’s easier for you or someone else to figure out how a proce- dure works six months or a year later when updates or modifications need to be made. I’ve seen my share of programs using huge everything-but-the-kitchen-sink procedures that were basically scrapped rather than updated because it was easier to rewrite than it was to figure out what was going on. This is an avoidable shame. Finally, by factoring your code, you have an increased ability to improve performance. For exam- ple, you may have an application that calls a routine to find a particular item in a range. In an unfac- tored application, different procedures may implement their own search algorithm to find an item in a range. It may not be an easy matter to modify each procedure to use a more efficient search algo- rithm. A factored application has one search method that’s used by any procedure that needs to search a range. By modifying the search algorithm in the search method, all of the procedures using the method will benefit from the increased performance. Think Like an Environmentalist One of the quickest ways an application can annoy or alienate a user is by operating like a toxic man- ufacturing factory located in Yellowstone National Park. Like a contemptible website that spawns countless pop-up windows, these programs go about rearranging options, menus, shortcut keys, and other aspects of Excel with reckless abandon. Programs should respect the environment that they operate in and respect the settings and pref- erences of the user. A conscientious program should ◆ Leave things as it finds them including menus and Excel option settings. ◆ Not reassign existing shortcut keys or mouse actions unless it gives the user the opportunity to turn this functionality on/off. ◆ Provide the user with reasonable preference/configuration options. ◆ Keep the user informed as to what is going on in an unobtrusive way such as by using the status bar. 4281book.fm Page 288 Sunday, February 29, 2004 5:12 PM 288 CHAPTER 13 EXCEL DEVELOPMENT BEST PRACTICES Note User interface coverage begins in Chapter 18. The goal is that when a user closes the application’s workbook (or turns off the add-in), the Excel user interface should look exactly like it did before the application started—down to the last setting. Use Literal Values with Care Literal (“hard-coded”) values can be maintenance nightmares and should be used cautiously. You can use literal values in many different ways. Some of the more common uses for these values within an Excel application include ◆ Range addresses ◆ Row numbers ◆ Column numbers ◆ Worksheet names ◆ Workbook names ◆ Database connection information In the last chapter, I presented the Setting and Settings classes. You can use these classes to move these kinds of things out of your VBA code and onto a worksheet where you can manage them better. Although this has the benefit of centralizing the handling of literal values, it doesn’t eliminate literal values from your code, because setting names are literal values. However, you can validate that a set- ting name exists before you use it to eliminate the risk normally associated with using a literal value. Use Syntax Highlighting In Chapter 2, I mentioned that syntax highlighting is something that offers a lot of benefit, but that I rarely see people take advantage of it. Well, I should clarify. Nearly everyone uses syntax highlighting; it’s just that hardly anyone deviates from the default settings. The chief benefit of using syntax high- lighting is that you can instantly identify literal values in your code. Now, literal values aren’t always a bad thing. However, they can be problematic when it comes to maintaining an application. Unfortunately, the black and white pictures in this book aren’t going to help prove how useful syn- tax highlighting is. It’s really something you need to try for yourself. Table 13.2 shows the syntax highlighting settings that I like to use. Try these out to start with. Table 13.2: Example Code Color Settings Code Element Foreground Color Background Color Normal Text Red Light Gray Comment Text Light Green Light Gray Keyword Text Bright Blue Light Gray Identifier Text Black Light Gray 4281book.fm Page 289 Sunday, February 29, 2004 5:12 PM 289 USE LITERAL VALUES WITH CARE Using this syntax-highlighting scheme, when you view code in the VBE, literal values will stand out like a sore thumb because they’ll appear as red text. Anywhere you see red text, you should pause and consider the way the literal value is being used and evaluate the likelihood that it will be a source of maintenance problems down the road. Manage Literal Values Centrally One of the risks associated with literal values is that if you need to modify a specific literal value, you need to be sure to look in every possible procedure that may be using the literal value to make sure each instance gets updated. This has two drawbacks: first, you may not get everything updated cor- rectly because it can be easy to overlook something; and second, it’s not very efficient to look through all of the procedures in a project. You can use Edit � Replace to help ease this issue, but even this method isn’t foolproof. It’s far more efficient to manage literal values centrally. You can do this in a lot of different ways including using private or public constants, storing data on a worksheet, using workbook names, or using the Windows registry. Occasionally, you’ll need to employ more than one of these methods. I’ll cover each of these methods in more detail in the following sections. Private Constants At a minimum, it’s a good idea to assign literal values to constants at the top of a module. Addition- ally, you should use the Private keyword in the declaration so that the constant can’t be seen by other procedures outside the module. The main benefit of using constants in your code rather than one of the other methods listed is that constants give you the best performance. You should consider using private constants when the constant value and name is unique to the given module and you don’t want the value to be used by procedures in any other modules. Public Constants If you need to refer to a literal value, you can assign a literal value to a public global constant rather than a private module-level constant. If you use global constants rather than private constants, then conceivably you might need to go to only one location in your project to update constant values. Like module-level constants, global constants offer the best performance when compared to the methods presented in the following sections. You should consider using public constants over private constants for two reasons. One scenario is where you need to define a constant that procedures will use in more than one module. For example, perhaps you define a constant that defines the application’s name: Public Const APP_NAME = "Budget Plus" Another reason to use public constants instead of private constants is that you can consolidate all of the constants in your application in one physical location. For example, you could create a module named CONSTANTS that serves as a container for all of the defined constants in your application. The benefit of this is that you don’t have to search for constants in each module to make any updates. If you’re in doubt about whether to define a private versus a public constant, I’d suggest that you make the constant public. 4281book.fm Page 290 Sunday, February 29, 2004 5:12 PM 290 CHAPTER 13 EXCEL DEVELOPMENT BEST PRACTICES Worksheet-Based Values The Setting and Settings classes presented in the last chapter are a prime example of the worksheet- based approach. The advantage of this approach is that it removes literal values from the code. This allows someone to maintain or alter the literal values without using the VBE. You’ll find this handy on occasions when the person who needs to modify the values isn’t a developer and isn’t comfortable working in the VBE. Alternatively, maybe you want to allow someone the ability to change these val- ues but you don’t want to give them the ability to view the code (i.e., you locked the VBA project for viewing). In these situations, you can place literal values on a worksheet and have procedures refer to the appropriate location on a worksheet to read the literal value. Note Check out the Setting and Settings classes. They are presented in detail in Chapter 12. If you don’t need the comprehensive functionality provided by the Setting and Settings classes, you could do something as simple as defining a range name that refers to the range where the value is located. For example, let’s say you created a range name “FISCAL_YEAR” that refers to a cell that stores the current fiscal year. You could easily retrieve the value in your code using the following statement. ThisWorkbook.Names("Fiscal_Year").RefersToRange In order to be a little more robust, you could validate that the name exists before using it in this manner. You may wonder if this really helps manage literal values. After all, isn’t the name of the named range (Fiscal_Year) a literal value? Yes, the name of the named range is a literal value, but it’s a good literal value if used correctly. The reason that this is a good literal value is that it’s a literal value that can be validated before using it in your code. Additionally, it enables us to move the real value (i.e., fiscal year = 2003) into a more easily accessible place where it is easier to manage. Note The use of named ranges is covered extensively in Chapter 8. Workbook Name Definitions for Setting Storage Another way to store settings is by using workbook or worksheet name definitions. I feel this is a little bit sneaky, but once in a while, it’s fun to be sneaky. Most Excel users aren’t aware that you can set up constants in a workbook using the name functionality. For example, you could create a name called SalesTaxRate and have it refer to the value .06 rather than a cell or range in the workbook, as shown in Figure 13.2. Figure 13.3 shows an example of how you use the name from a worksheet. Figure 13.2 You can set up names that refer to a value rather than a cell or range on a worksheet. 4281book.fm Page 291 Sunday, February 29, 2004 5:12 PM 291 USE LITERAL VALUES WITH CARE Figure 13.3 When you use the name in the work- book, you get the val- ue you assigned to it. If you do use this method of storing values, you need to use the Evaluate method of the Applica- tion object to retrieve the value associated with the name. Listing 13.2 demonstrates this. Listing 13.2: Retrieving Values Stored as a Workbook Name Using the Evaluate Method Sub TestWorkbookNameValue() Dim vValue As Variant vValue = Application.Names("SalesTaxRate").RefersTo Debug.Print "Value retrieved using RefersTo: " & vValue vValue = Application.Names("SalesTaxRate").Value Debug.Print "Value retrieved using Value: " & vValue ' this next line doesn't work because the name ' doesn't refer to a range. Intentionally commented out. ' vValue = Application.Names("SalesTaxRate").RefersToRange vValue = Application.Evaluate("SalesTaxRate") Debug.Print "Value retrieved using Evaluate: " & vValue End Sub This listing produces the following output. Value retrieved using RefersTo: =0.06 Value retrieved using Value: =0.06 Value retrieved using Evaluate: 0.06 Notice that if you do not use Evaluate, the value retrieved from the Name will include an equals sign (=). If the value is text data, you’ll also get the value enclosed in quotes. One of the primary benefits of this method is that you can be consistent in how you use literal val- ues within the workbook and your VBA code. For example, the SalesTaxRate name in Listing 13.2 could also be used in any worksheet formulas that need to reference the sales tax rate. 4281book.fm Page 292 Sunday, February 29, 2004 5:12 PM 292 CHAPTER 13 EXCEL DEVELOPMENT BEST PRACTICES Figure 13.4 Excel uses the registry to store configuration information. Using the Windows Registry for Storing Values Another option for storing literal values is the Windows registry. In fact, if you browsed the registry using the Registry Editor, you’d see that this is a common way for Windows programs to store con- figuration information. In Figure 13.4, you can see some of the registry settings used by Excel. Note To view the registry, choose Start � Run, type regedit, and click OK. Warning Use extreme caution using the Registry Editor. Never modify registry information unless you are 100 percent sure of the consequences. Individual settings in the registry are referred to as keys. VBA provides a few functions for writing to and reading from the registry. The function SaveSetting creates a new registry key or updates an existing registry key. The function GetSetting retrieves the value associated with a registry key. I’ll let you take a stab at what DeleteSetting does. Finally, a function called GetAllSettings retrieves a list of keys and the values associated with a certain application and section. These functions are pretty easy to use as is demonstrated by Listing 13.3. Listing 13.3:Working with the Registry Using the VBA Registry Functions Sub ExperimentWithRegistry() Dim vaKeys As Variant ' create new registry entries 4281book.fm Page 293 Sunday, February 29, 2004 5:12 PM 293 USE LITERAL VALUES WITH CARE SaveSetting "XLTest", "General", "App_Name", "XLTest" SaveSetting "XLTest", "General", "App_Version", "1.0.0" SaveSetting "XLTest", "General", "App_Date", "10/11/2003" PrintRegistrySettings ' update a setting SaveSetting "XLTest", "General", "App_Version", "1.0.1" PrintRegistrySettings ' get all settings in an array vaKeys = GetAllSettings("XLTest", "General") PrintAllSettings vaKeys ' delete settings DeleteSetting "XLTest", "General", "App_Name" DeleteSetting "XLTest", "General", "App_Version" DeleteSetting "XLTest", "General", "App_Date" PrintRegistrySettings End Sub Sub PrintRegistrySettings() On Error Resume Next Debug.Print "Application Name: " & _ GetSetting("XLTest", "General", "App_Name") Debug.Print "Application Version: " & _ GetSetting("XLTest", "General", "App_Version") Debug.Print "Application Date: " & _ GetSetting("XLTest", "General", "App_Date") Debug.Print " " End Sub Sub PrintAllSettings(vaSettings As Variant) Dim nItem As Integer If IsArray(vaSettings) Then For nItem = 0 To UBound(vaSettings) Debug.Print vaSettings(nItem, 0) & ": " & _ vaSettings(nItem, 1) Next End If Debug.Print " " End Sub 4281book.fm Page 294 Sunday, February 29, 2004 5:12 PM 294 CHAPTER 13 EXCEL DEVELOPMENT BEST PRACTICES This listing produces the following output: Application Name: XLTest Application Version: 1.0.0 Application Date: 10/11/2003 Application Name: XLTest Application Version: 1.0.1 Application Date: 10/11/2003 App_Name: XLTest App_Version: 1.0.1 App_Date: 10/11/2003 Application Name: Application Version: Application Date: Notice that if you use the GetAllSettings function, a two-dimensional variant array is returned. The first dimension represents each setting returned whereas the second dimension is one of two items: the key name or the key value. Note Registry entries created with SaveSetting are written to HKEY_CURRENT_USER\Software\VB and VBA Program Settings\ . Looking Up Values From a Database It’s possible to store these kinds of values in a database. The benefit of this approach is that it’s possible to change the settings for all of the users without having to distribute new copies of the workbook or application. It also offers the most flexibility regarding securing the values. The main drawbacks of this method are that it requires a database connection and it’s slower than the other methods. If you don’t want to assume a constant database connection, you could use one of the other approaches for short- term needs and occasionally connect to the database for updates. Consider using a database to store literal values that have short half-lives. That is, literal values that are likely to change over the life of the application. The more difficult it is to distribute new versions of the application, the more attractive this option becomes. For example, if the application is distrib- uted to hundreds or thousands of users across the organization, it may be cost-effective to have an application that knows how to update itself rather than redistribute new versions of the application or otherwise force users to always “check the intranet for the latest version.” Note Database coverage begins in Chapter 16. Using XML for Persistent Settings One of the many things that you can use XML (Extensible Markup Language) for is to create a mod- ern-day initialization file. In fact, some of the most exciting new features in Excel 2003 rely heavily on XML for this purpose. [...]... the VBA aspect of developing Excel applications, this chapter wouldn’t be complete without mentioning some practical advice regarding the general layout of an Excel application In Chapter 22, I describe various application-distribution strategies and techniques such as templates, add-ins, and standard Excel workbooks For the purposes of this section, I’m assuming that you’re developing a standard Excel. .. a destination Enjoy the trip! With the next chapter, I’ll begin my coverage of the techniques related to working with external data and programs including databases, text files, and XML The first topic in this part, however, is integrating with other applications such as Microsoft Word Part 4 Working with External Data In this section: ◆ ◆ ◆ ◆ Chapter 14: Integrating with Other Applications Chapter... Text Files in Your Solution Chapter 16: Dealing with Databases Chapter 17: XL(M) = XML This page intentionally left blank Chapter 14 Integrating with Other Applications Although Excel is a versatile application, try as some people might, they can’t make it do everything Thankfully, it’s possible to embed or link documents created using other applications into an Excel doc­ ument Documents created using... just bored, you can do all sorts of weird things For example, Figure 14.2 is an Excel worksheet inside an embedded Word document inside another Excel worksheet The son-in-law of my friend’s cousin’s girlfriend showed me that trick 303 304 CHAPTER 14 INTEGRATING WITH OTHER APPLICATIONS Figure 14.2 Embed Excel in Word in Excel? You can create all sorts of combinations by embedding different combinations... there, you use the class library as if you were using it natively This, of course, assumes that you’re familiar with the other application’s class library Just as it’s hard to do anything in Excel with out some knowledge of Excel s object model, it’s difficult to do anything useful in Word without some knowledge of Word’s object model So how do you access another application’s class library? Well, it... PowerPoint Set ppt = New PowerPoint.Application ' Create a new presentation Set pres = ppt. Presentations.Add pres.ApplyTemplate _ "c:\program files\microsoft office\templates" & _ OLE IS GREAT; AUTOMATION IS BETTER "\presentation designs\maple.pot" With pres.Slides.Add(1, ppLayoutTitle) Shapes(1).TextFrame.TextRange.Text = "October Sales Analysis" Shapes(2).TextFrame.TextRange.Text = "11/5 /2003" End With '... version of COM that came into existence with Windows 2000 Automation Automation is the term that refers to the concept of controlling one application from within another application 302 CHAPTER 14 INTEGRATING WITH OTHER APPLICATIONS Note Microsoft has a newer software architecture called NET .NET is a totally new architecture that is not directly compatible with COM technologies (though you can have... prepare in Excel Because your company has invested in Microsoft Analysis Services to facilitate rapid analysis in Excel, it only takes you a mat­ ter of minutes to gather the data required for the report The Problem The problem is that the presentation needs to use PowerPoint Consequently, you spend most of your time shuffling data from Excel to PowerPoint manually You have already experimented with object... create a single Excel workbook and a single PowerPoint presentation The presentation contains linked Excel data Each month, all you need to do is refresh the data in Excel and the PowerPoint presentation updates automatically Then all you need to do is change the bullet points in the presentation as necessary In theory, this should work just fine However, you encounter two problems with this approach... the wrong file For example, October’s presentation may have a link to September’s Excel workbook The second problem is also related to linking The presentation file needs to be portable so that your boss and others can use it without having to distribute the Excel file as well This means you really need to embed the Excel file rather than link to it If you embed, of course, you don’t get the intended . differences between developing in VBA with Excel as a host and developing a stand- alone application with a traditional programming language is that when you develop in Excel, you don’t have 100-percent. which you can use XML with Excel. Smart Workbook Design Although this book focuses on the VBA aspect of developing Excel applications, this chapter wouldn’t be complete without mentioning some. levels of reuse: the first level is reuse within the same module or project and the second level is reuse within other projects. An exciting thing happens with factored code— you experience a wonderful

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

TỪ KHÓA LIÊN QUAN