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

Mastering Excel 2003 Programming with VBA phần 9 ppt

61 274 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,74 MB

Nội dung

4281book.fm Page 469 Sunday, February 29, 2004 5:12 PM 469 FORMS ARE MEANT TO BE SHOWN There isn’t much to this one, is there? Granted, this is a simple form, but usually the code in the event procedures associated with the various controls on a form is fairly compact. Every form you cre- ate will use either the Activate or Initialize event to populate its controls before the form actually gets displayed to the user. The Initialize event only occurs once in a form’s lifetime; it is the first thing to happen when a form gets created. The Activate event can occur multiple times in a form’s lifetime. An Activate event typically, though not necessarily, occurs just after the Initialize event. You’ll see the difference between these two events later in the chapter in the section titled “The Form Lifecycle.” For now, you can see that I’ve used the Initialize event to populate the text box with the name of the active sheet and then preselected the text in the text box. If I didn’t preselect the text, the cursor would appear at the end of the text, which is not very convenient from a user’s perspective. The only other comment I have regarding this listing is that the SaveSheetName procedure is called by the cmdOK click event procedure. In order to keep it simple, I’m not bothering to check if the user actually changes the sheet name or not. I mean, what’s the point? Does it make a difference if the sheet name is set to the exact same value? I think not. Also, rather than worry about validating the name entered, it is much easier to let Excel do the validating for me and just continue on my busi- ness if an error occurs. If this were a production type application, I would probably want to inspect any error that does occur so that I can notify the user why the name couldn’t be changed. Forms Are Meant to Be Shown Of course, you can’t expect your users to open the VBE, select the form they want to run, and then press F5 to run it. You need some way to allow them to see the form or show it when certain events happen. Depending on your needs, you have a few ways to go about displaying a form to a user: using the Show method, using the Load statement, or instantiating a form as an object. Show First, Ask Questions Later The easiest and perhaps most frequently used method is the form’s Show method. The syntax of Show is frm.Show [modal] The modal parameter controls a key behavior of a form. A form can be modal (vbModal) or modeless (vbModeless). When a form is modal, the user must complete her interaction with the form before she can use any other aspect of Excel. Additionally, any subsequent code is not executed until the form is hidden or unloaded. When a form is modeless, any subsequent code is executed as it’s encountered. Listing 20.2 presents an example that displays the Simple form developed previously in the chapter. The SimpleFormExample shows the form twice—once as a modal form and once as a modeless form. Listing 20.2: Using the Show Method to Display a Form Sub SimpleFormExample() ' Show form modally ShowSimpleForm True MsgBox "OK - Same form now, but modeless.", vbOKOnly 4281book.fm Page 470 Sunday, February 29, 2004 5:12 PM 470 CHAPTER 20 USER FORM CONSTRUCTION ' Show form modeless ShowSimpleForm False MsgBox "Exiting the SimpleFormExample procedure.", vbOKOnly End Sub ' Display the simple form Private Sub ShowSimpleForm(bModal As Boolean) If bModal Then frmSimpleForm.Show vbModal Else frmSimpleForm.Show vbModeless End If End Sub When you run the SimpleFormExample, notice that you don’t get the first message box until after you dismiss the form the first time. The second message box, however, is displayed immediately after the form is displayed the second time—before you even get a chance to dismiss the form. As you run this example, it would also be beneficial to try and interact with Excel as each form is displayed so that you can experience the full difference between these two behaviors. Switching from modal to modeless or vice versa often causes trouble because it affects how your code executes and thus will violate the implicit assumptions you made regarding the execution of your code when you originally coded it. Therefore, you should choose wisely the first time. In fact, the Simple form dem- onstrates the impact of this. Simple form was developed in a manner that assumed the form would be modal. Consequently, Simple form works by modifying the name of the active sheet. When you run Simple form as a modeless form, it is possible to change worksheets while the form is still open. If you change the name of the sheet and then change worksheets before clicking OK, Simple form changes the name of the currently active sheet rather than the sheet that was active when Simple form was originally displayed. Load and Show Although most of the time you will simply use the Show method to display forms, occasionally you’ll need a way to manipulate the form prior to displaying it to the user. In order to achieve this, you need to use the Load statement to load the form into memory. Once the form is loaded into memory (but not displayed to the user), you can interact with the form programmatically prior to displaying the form using the Show method as before. Load gives you a lot more flexibility than just using Show alone. In fact, when you use Show without using Load, Show calls Load internally for you. Listing 20.3 presents an example that demonstrates this method. Listing 20.3: Loading a Form into Memory Prior to Displaying It ' Modify the simple form before showing it Sub ModifySimpleForm() Dim sNewCaption As String ' Load the form into memory 4281book.fm Page 471 Sunday, February 29, 2004 5:12 PM 471 FORMS ARE MEANT TO BE SHOWN Load frmSimpleForm ' Prompt for a new caption sNewCaption = InputBox("Enter a caption for the form.") ' Set the new caption frmSimpleForm.Caption = sNewCaption ' Show the form frmSimpleForm.Show ' Show another instance of the form MsgBox "OK - same form again except with default caption", vbOKOnly frmSimpleForm.Show End Sub In addition to demonstrating how to use the Load then Show method of displaying a form, this listing also helps illuminate another facet of using forms. As you’ll see in the following section, a form is really a fancy class module that knows how to display user interface controls. Because of this, when you modify the Caption property for one instance of the form, you do not affect any other form instances. This fact is illustrated in this listing when the last statement shows a (second) instance of the Simple form by displaying a new form using the Show method. Classy Forms So far, you have seen that using the Load then Show method for displaying a form offers more flex- ibility than using Show alone. You can wring even more flexibility out of your forms by designing them and using them in the same manner that you would design and use any other class module. As I mentioned earlier, a form module is really a special kind of class module. You can use your forms exactly as you would any other class. In order to take advantage of this fact, you should design your forms appropriately. The Simple form you developed earlier suffers from one flaw that limits its flexibility. In Listing 20.1, you can see that both the cmdOK_Click and cmdCancel_Click procedures contain one fatal (liter- ally) statement—Unload Me. Unload is a VBA statement that unloads an object from memory, whereas Me is a way to get an object to refer to itself. In order to have the ultimate amount of flex- ibility, you should place the responsibility of destroying a form with the code that instantiates it. Note Although it is good practice to explicitly dereference objects when you’re done using them, VBA automatically dereferences objects that fall out of scope. For example, an object that is declared local to a procedure is automatically de- referenced sometime after the procedure finishes executing. Though traditionally the former two methods for displaying a form are taught, this method isn’t that radical of an idea. With any other object that you use, either objects that you develop or native objects from the Excel object model, if you instantiate an object, then it’s yours to use until you deref- erence it by setting it to Nothing. Objects rarely decide to unload themselves (though VBA may unload them once it deems that they are no longer being used). 4281book.fm Page 472 Sunday, February 29, 2004 5:12 PM 472 CHAPTER 20 USER FORM CONSTRUCTION Figure 20.5 The Classy form That being said, you could argue that the two methods for displaying forms that I’ve already pre- sented are unorthodox; I wouldn’t disagree. Anyway, perhaps a quick example would clear all of this up for you. In order to demonstrate this concept, I developed the Classy form shown in Figure 20.5. All Classy does is allow you to enter some text in a text box and click OK. Pretty boring, eh? Table 20.4 provides the control properties that I modified when creating Classy. Table 20.4: Classy Control Property Values Control Property Value Lable1 (Name) lblStuff Label1 Accelerator E TextBox1 (Name) txtStuff CommandButton1 (Name) cmdOK CommandButton1 Caption OK CommandButton1 Default True In order to make this form work, I only needed to code one event procedure, as shown in Listing 20.4. Listing 20.4: Classy’s Code Option Explicit Private Sub cmdOK_Click() Me.Hide End Sub 4281book.fm Page 473 Sunday, February 29, 2004 5:12 PM 473 FORMS ARE MEANT TO BE SHOWN With those few lines of code, I have finished a form that is fundamentally different from the pre- vious form. In the previous form, the Simple form unloaded itself when you clicked OK. Classy, on the other hand, just hides itself. As a result, the form is still accessible in memory even though the user can’t see it. Listing 20.5 provides an example of how to use such a form. Listing 20.5: A Classy Example Sub ClassyFormExample() Dim frm As frmClassy Dim vResponse As Variant ' Instantiate frmClassy ' This has the same effect as: Load frmClassy Set frm = New frmClassy ' Prefill the edit box with a value (just for fun) frm.txtStuff = "Good Stuff" frm.Show ' Form is now hidden, but you can still manipulate it vResponse = MsgBox("The Classy form text box says: " & _ frm.txtStuff & ". View again?", vbYesNo) If vResponse = vbYes Then ' The form is still alive - show it ' See - txtStuff has the same value as before frm.Show End If ' RIP o Classy one Set frm = Nothing End Sub Doesn’t this kind of coding style look familiar? This is the same way you’d go about using an object. In the first declaration statement, I declare a variable named frm that is typed as an frm- Classy object. Two statements later, I create a new instance of an frmClassy. This statement per- forms the exact same process you’d get if you used the Load statement. As you saw in the Load and Show example (Listing 20.3), once you create a new instance of the form, you can set various form property values programmatically. Once you click OK after displaying Classy, Classy is hidden by the cmdClick event procedure. If you click Yes in response to the message box, Classy is seemingly revived from the dead—complete with all of its values as you left them before you clicked OK. Finally, the next to last statement unloads Classy from memory by setting the variable used to point to the form to Nothing. As another example, consider Listing 20.6. This listing creates two separate instances of Classy. 4281book.fm Page 474 Sunday, February 29, 2004 5:12 PM 474 CHAPTER 20 USER FORM CONSTRUCTION Listing 20.6: Multiple Instances of the Classy Form Sub ClassyFormExample2() Dim frm1 As frmClassy Dim frm2 As frmClassy Set frm1 = New frmClassy Set frm2 = New frmClassy frm1.Caption = "I am Classy" frm1.Show frm2.Caption = "I am Classy too." frm2.txtStuff = "I am Classy said '" & frm1.txtStuff & "'" frm2.Show Set frm1 = Nothing Set frm2 = Nothing End Sub This listing helps drive home the point that forms are classes and can be used as such, particularly when you don’t destroy the form from within by embedding the Unload statement in one of the form’s event procedures. Listing 20.6 creates two instances of frmClassy. After you close the first instance, the second instance reads what you entered in the first instance and tells you what you said. The Form Lifecycle As I mentioned earlier, you use one of two form event procedures to perform form initialization chores: either Activate or Initialize. The Initialize event occurs in response to the form being loaded into memory, whereas the Activate event occurs in response to the form being shown. That is why Ini- tialize always runs once and only once for a given form instance whereas Activate may occur multiple times. Depending on which of the methods you use to display the form, the implications of choosing Activate and Initialize can yield drastically different results. Choosing the proper event to respond to doesn’t stop with the choice between using Activate or Initialize. Nearly every control you add to a form requires you to handle one or more of its events in order to provide any useful functionality. Many times you will identify more than one event for a par- ticular control that may serve as a trigger to run code that implements some sort of behavior. In order to make an informed decision as to which event procedure to use, I often find it helpful to trace the events that occur in a form during the development process. You can trace events by including a sim- ple statement in each event procedure of interest that either displays a message box, writes a message to the Immediate window using Debug.Print, or records each event on a worksheet in your workbook. Figure 20.6 shows an example of a form that traces events by writing events of interest to a worksheet. 4281book.fm Page 475 Sunday, February 29, 2004 5:12 PM 475 THE FORM LIFECYCLE Figure 20.6 The Event Tracing form in action In order to have plenty of events to play with, the form has controls on it that implement random functionality that changes the appearance of a worksheet with a code name of wsEventTracing. You can set the code name of a worksheet in the VBE by selecting the worksheet that you want to rename under the Microsoft Excel Objects item in the Project Explorer window and changing the Name property in the Properties window. As you can see in Figure 20.6, I placed the text “Control” and “Event” in cells A1 and B1 respectively. Table 20.5 lists the properties I modified as I added controls to the Event Tracing form. Table 20.5: Event Tracing Control Properties Control Property Value UserForm (Name) frmEventTracing frmEventTracing Caption Event Tracing Label (Name) lblWorksheetName lblWorksheetName Caption Worksheet Name TextBox (Name) txtName CheckBox (Name) chkGridlines chkGridlines Caption Gridlines CheckBox (Name) chkWeirdFont 4281book.fm Page 476 Sunday, February 29, 2004 5:12 PM 476 CHAPTER 20 USER FORM CONSTRUCTION Table 20.5: Event Tracing Control Properties (continued) Control Property Value chkWeirdFont Caption Use Weird Font Frame (Name) frmOptions frmOptions Caption Font Color Options OptionButton (Name) optBlack optBlack Caption Black OptionButton (Name) optBlue optBlue Caption Blue OptionButton (Name) optGreen optGreen Caption Green CommandButton (Name) cmdHide cmdHide Accelerator H cmdHide Caption Hide CommandButton (Name) cmdOK cmdOK Caption OK cmdOK Default True Label (Name) lblSummary Listing 20.7 contains the code necessary to implement the functionality of the Event Tracing form. Listing 20.7: Tracing Form Events Option Explicit Dim mws As Worksheet Dim msColor As String Private Sub chkGridlines_Click() RecordEvent chkGridlines.Name, "Click" ActiveWindow.DisplayGridlines = chkGridlines.Value SetSummary End Sub Private Sub chkWeirdFont_Click() ' It is possible that the font "Bradley Hand ITC" 4281book.fm Page 477 Sunday, February 29, 2004 5:12 PM 477 THE FORM LIFECYCLE ' may not be present on every PC On Error Resume Next RecordEvent chkWeirdFont.Name, "Click" If chkWeirdFont.Value Then mws.Cells.Font.Name = "Bradley Hand ITC" Else mws.Cells.Font.Name = "Arial" End If SetSummary End Sub Private Sub cmdHide_Click() RecordEvent cmdHide.Name, "Click" Me.Hide ' Pause for a brief period and ' then reshow the form Application.Wait Now + 0.00003 Me.Show End Sub Private Sub cmdOK_Click() RecordEvent cmdOK.Name, "Click" Unload Me End Sub Private Function RecordEvent(sControl As String, sEvent As String) Dim rg As Range Set rg = mws.Cells(65536, 1).End(xlUp).Offset(1, 0) rg.Value = sControl rg.Offset(0, 1).Value = sEvent Set rg = Nothing End Function Private Sub frmOptions_Click() RecordEvent frmOptions.Name, "Click" End Sub Private Sub optBlack_Change() RecordEvent optBlack.Name, "Change" End Sub Private Sub optBlack_Click() RecordEvent optBlack.Name, "Click" msColor = "black" mws.Cells.Font.Color = vbBlack [...]... using VBA That’s right—they are one of the best new features of Excel 2003 and you cannot develop solutions incorporating them with VBA alone As a VBA developer, this disappoints me immensely Look on the bright side, though; you can use one of VBA s relatives—either Visual Basic 6.0 or Visual Basic NET Another thing that may disappoint some readers is that you’ll need to be fairly proficient with XML... Figure 21.3 A smarter loan amor­ tization worksheet 495 496 CHAPTER 21 ONE SMART COOKIE: SMART DOCUMENTS WITH EXCEL 2003 By providing task-specific guidance and functionality from a single location on the document (or screen), a smart document can tame a complex process so that a user can complete the process without any, or as much training, and without having an in-depth knowledge of the structure... "DisableManifestSecurityCheck"=dword:00000001 2 Save the file as DisableManifestSecurityCheck.reg 3 Execute the file by double-clicking it in Windows Explorer 497 498 CHAPTER 21 ONE SMART COOKIE: SMART DOCUMENTS WITH EXCEL 2003 After you disable expansion pack security in this manner, you will be presented with the following dialog box when you attempt to add an expansion pack In addition to the security checks applied to the manifest... the user clicks OK or Cancel rather than unloaded If you unload this form from within rather than hide it, you won’t have a convenient way to tell the procedure that calls the form what password the user enters Listing 20 .9 presents the code required by the Password form 4 89 490 CHAPTER 20 USER FORM CONSTRUCTION Listing 20 .9: Event Procedures for the Password Form Option Explicit Dim msPassword As String... understand just what a smart document is and how a document comes to acquire intelligence 494 CHAPTER 21 ONE SMART COOKIE: SMART DOCUMENTS WITH EXCEL 2003 Being Smart Has Benefits A smart document delivers its “smarts” via the task pane The task pane is the multitalented window fragment that appears when you initially start Excel To display the task pane, press Ctrl + F1 (or View � Task Pane) I call the task... to a user’s actions, 491 492 CHAPTER 20 USER FORM CONSTRUCTION either you can use the Unload statement along with the name of the form (or the Me keyword when used within the form itself), or you can use the Hide method followed up by the Unload statement The trickiest aspect of form development (other than trivial forms) is handling all of the events appropriately and dealing with the, sometimes complex,... Chapter 21 One Smart Cookie: Smart Documents with Excel 2003 The most cutting edge user interface concept in Microsoft Office 2003 is the concept of a smart document Smart documents are documents that respond to a user’s actions in order to provide relevant assistance to the user as he works I feel compelled to tell you that some readers are going to be disappointed with the information I’m about to deliver... So Smart Document (with Lots of Potential) The first place to start when developing a smart document is with the document itself You have enough to do in this example in addition to creating a document from scratch, so I created a loan amortization workbook based on the Loan Amortization template included with Excel To set up this workbook, follow these steps 1 Choose File � New in Excel A SMART DOCUMENT... 21.1: A Loan Amortization Schema (LoanAmortization.xsd) . 4281book.fm Page 4 69 Sunday, February 29, 2004 5:12 PM 4 69 FORMS ARE MEANT TO BE SHOWN There isn’t much to this one, is there? Granted,. Error GoTo ErrHandler ' Refer via worksheet code name 4281book.fm Page 4 79 Sunday, February 29, 2004 5:12 PM 4 79 THE FORM LIFECYCLE ' since this form can change the display name Set. to dismiss the form. As you run this example, it would also be beneficial to try and interact with Excel as each form is displayed so that you can experience the full difference between these

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