Excel 2002 Power Programming with VBA phần 5 pot

99 275 0
Excel 2002 Power Programming with VBA phần 5 pot

Đ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

358 Part IV ✦ Working with UserForms Table 12-1 Codes to Determine the Data Type Returned by Excel’s InputBox Method Code Meaning 0 A formula 1 A number 2 A string (text) 4 A logical value (True or False) 8 A cell reference, as a range object 16 An error value, such as #N/A 64 An array of values Excel’s InputBox method is quite versatile. To allow more than one data type to be returned, use the sum of the pertinent codes. For example, to display an input box that can accept text or numbers, set type equal to 3 (that is, 1 + 2, or “number” plus “text”). If you use 8 for the type argument, the user can enter a cell or range address manually, or point to a range in the worksheet. The EraseRange procedure, which follows, uses the InputBox method to allow the user to select a range to erase (see Figure 12-2). The user can either type the range address manually, or use the mouse to select the range in the sheet. The InputBox method with a type argument of 8 returns a Range object (note the Set keyword). This range is then erased (by using the Clear method). The default value displayed in the input box is the current selection’s address. The On Error statement ends the procedure if the input box is canceled. Sub EraseRange() Dim UserRange As Range DefaultRange = Selection.Address On Error GoTo Canceled Set UserRange = Application.InputBox _ (Prompt:=”Range to erase:”, _ Title:=”Range Erase”, _ Default:=DefaultRange, _ Type:=8) UserRange.Clear UserRange.Select Canceled: End Sub 4799-2 ch12.F 6/11/01 9:32 AM Page 358 359 Chapter 12 ✦ Custom Dialog Box Alternatives Figure 12-2: Using the InputBox method to specify a range Yet another advantage of using Excel’s InputBox method is that Excel performs input validation automatically. In the GetRange example, if you enter something other than a range address, Excel displays an informative message and lets the user try again (see Figure 12-3). Figure 12-3: Excel’s InputBox method performs validation automatically. VBA’s MsgBox Function VBA’s MsgBox function is an easy way to display a message to the user, or to get a simple response (such as OK or Cancel). I use the MsgBox function in many of this book’s examples as a way to display a variable’s value. The official syntax for MsgBox is as follows: MsgBox(prompt[,buttons][,title][,helpfile, context]) 4799-2 ch12.F 6/11/01 9:32 AM Page 359 360 Part IV ✦ Working with UserForms prompt Required. The text displayed in the message box. buttons Optional. A numeric expression that determines which buttons and icon are displayed in the message box. See Table 12-2. title Optional. The caption in the message box window. helpFile, context Optional. The helpfile and help topic. You can easily customize your message boxes because of the flexibility of the but- tons argument. (Table 12-2 lists the many constants that you can use for this argu- ment.) You can specify which buttons to display, whether an icon appears, and which button is the default. Table 12-2 Constants Used for Buttons in the MsgBox Function Constant Value Description vbOKOnly 0 Display OK button only vbOKCancel 1 Display OK and Cancel buttons vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons vbYesNoCancel 3 Display Yes, No, and Cancel buttons vbYesNo 4 Display Yes and No buttons vbRetryCancel 5 Display Retry and Cancel buttons vbCritical 16 Display Critical Message icon vbQuestion 32 Display Warning Query icon vbExclamation 48 Display Warning Message icon vbInformation 64 Display Information Message icon vbDefaultButton1 0 First button is default vbDefaultButton2 256 Second button is default vbDefaultButton3 512 Third button is default vbDefaultButton4 768 Fourth button is default vbSystemModal 4096 All applications are suspended until the user responds to the message box (may not work under all conditions) You can use the MsgBox function by itself (to simply display a message) or assign its result to a variable. When MsgBox does return a result, it represents the button clicked by the user. The following example displays a message and does not return a result: 4799-2 ch12.F 6/11/01 9:32 AM Page 360 361 Chapter 12 ✦ Custom Dialog Box Alternatives Sub MsgBoxDemo() MsgBox “Click OK to continue” End Sub To get a response from a message box, you can assign the results of the MsgBox function to a variable. In the following code, I use some built-in constants (described in Table 12-3) to make it easier to work with the values returned by MsgBox: Sub GetAnswer() Ans = MsgBox(“Continue?”, vbYesNo) Select Case Ans Case vbYes ‘ [code if Ans is Yes] Case vbNo ‘ [code if Ans is No] End Select End Sub Table 12-3 Constants Used for MsgBox Return Value Constant Value Button Clicked vbOK 1OK vbCancel 2 Cancel vbAbort 3 Abort vbRetry 4 Retry vbIgnore 5 Ignore vbYes 6Yes vbNo 7No Actually, it’s not even necessary to use a variable to utilize the result of a message box. The following procedure displays a message box with Yes and No buttons. If the user doesn’t click the Yes button, the procedure ends. Sub GetAnswer2() If MsgBox(“Continue?”, vbYesNo) <> vbYes Then Exit Sub ‘ [code if Yes button is not clicked] End Sub The following function example uses a combination of constants to display a mes- sage box with a Yes button, a No button, and a question mark icon; the second but- ton is designated as the default button (see Figure 12-4). For simplicity, I assigned these constants to the Config variable. 4799-2 ch12.F 6/11/01 9:32 AM Page 361 362 Part IV ✦ Working with UserForms Private Function ContinueProcedure() As Boolean Dim Config As Integer Dim Ans As Integer Config = vbYesNo + vbQuestion + vbDefaultButton2 Ans = MsgBox(“An error occurred. Continue?”, Config) If Ans = vbYes Then ContinueProcedure = True _ Else ContinueProcedure = False End Function The ContinueProcedure function can be called from another procedure. For exam- ple, the following statement calls the ContinueProcedure function (which displays the message box). If the function returns False (that is, the user selects No), the procedure ends. Otherwise, the next statement would be executed. If Not ContinueProcedure Then Exit Sub Figure 12-4: The buttons argument of the MsgBox function determines which buttons appear. If you would like to force a line break in the message, use the vbCrLf (or vbNewLine) constant in the text. The following example displays the message in three lines: Sub MultiLine() Dim Msg As String Msg = “This is the first line” & vbCrLf Msg = Msg & “Second line” & vbCrLf Msg = Msg & “Last line” MsgBox Msg End Sub You can also insert a tab character by using the vbTab constant. The following pro- cedure uses a message box to display the values in a 20 × 8 range of cells (see Figure 12-5). It separates the columns by using a vbTab constant, and inserts a new line by using the vbCrLF constant. The MsgBox function accepts a maximum string length of 1,023 characters, which will limit the number of cells you can display. Sub ShowRange() Dim Msg As String Dim r As Integer, c As Integer Msg = “” 4799-2 ch12.F 6/11/01 9:32 AM Page 362 363 Chapter 12 ✦ Custom Dialog Box Alternatives For r = 1 To 20 For c = 1 To 8 Msg = Msg & Cells(r, c) & vbTab Next c Msg = Msg & vbCrLf Next r MsgBox Msg End Sub Chapter 15 includes a VBA example that emulates the MsgBox function. Cross- Reference Another Type of Message Box Excel can access the Windows Scripting Host (Wscript) and display another type of message box by using the Popup method of the Shell object. This alternative message box differs from the standard message box in two ways: It can dismiss itself after a specified period of time; and it’s possible to display the message box with no buttons. The following example displays a message box. If the user does not dismiss it within five seconds, it is dismissed automatically. Sub PopupDemo() Dim WshShell As IWshShell Dim Msg As String Set WshShell = CreateObject(“Wscript.Shell”) Msg = “This message will self-destruct in 5 seconds.” Title = “A friendly reminder” WshShell.Popup Msg, 5, Title, 7 + vbInformation Set WshShell = Nothing End Sub The first Set statement creates the Shell object and assigns it to the WshShell variable. The first argument for the Popup method represents the text to be displayed. The second argument specifies the number of seconds to display the message box. The third argument is the title bar text. The final argument specifies the buttons and icon to be displayed (it works just like the buttons argument for the MsgBox function). If you decide to use this alternate message box, be aware that system administrators often disable the Windows Scripting Host because of the threat of viruses. If the Windows Scripting Host is disabled, the code will generate an error. 4799-2 ch12.F 6/11/01 9:32 AM Page 363 364 Part IV ✦ Working with UserForms Figure 12-5: This message box displays text with tabs and line breaks. Excel’s GetOpenFilename Method If your application needs to ask the user for a filename, you can use the InputBox function. But this approach often leads to typographical errors. A better approach is to use the GetOpenFilename method of the Application object, which ensures that your application gets a valid filename (as well as its complete path). This method displays the normal Open dialog box (displayed when you select the File ➪ Open command) but does not actually open the file specified. Rather, the method returns a string that contains the path and filename selected by the user. Then you can do whatever you want with the filename. The syntax for this method is as follows (all arguments are optional): object.GetOpenFilename(FileFilter, FilterIndex, Title, ButtonText, MultiSelect) FileFilter Optional. A string specifying file-filtering criteria. FilterIndex Optional. The index numbers of the default file-filtering criteria. Title Optional. The title of the dialog box. If omitted, the title is “Open.” ButtonText For Macintosh only. MultiSelect Optional. If True, multiple filenames can be selected. The default value is False. 4799-2 ch12.F 6/11/01 9:32 AM Page 364 365 Chapter 12 ✦ Custom Dialog Box Alternatives The FileFilter argument determines what appears in the dialog box’s Files of type drop-down list. The argument consists of pairs of file filter strings followed by the wildcard file filter specification, with each part and each pair separated by commas. If omitted, this argument defaults to: “ All Files (*.*),*.*” Notice that the first part of this string (All Files (*.*)) is the text displayed in the Files of type drop-down list. The second part ( *.*) actually determines which files are displayed. The following instruction assigns a string to a variable named Filt. This string can then be used as a FileFilter argument for the GetOpenFilename method. In this case, the dialog box will allow the user to select from four different file types (plus an “all files” option). Notice that I used VBA’s line continuation sequence to set up the Filt variable; doing so makes it much easier to work with this rather compli- cated argument. Filt = “Text Files (*.txt),*.txt,” & _ “Lotus Files (*.prn),*.prn,” & _ “Comma Separated Files (*.csv),*.csv,” & _ “ASCII Files (*.asc),*.asc,” & _ “All Files (*.*),*.*” The FilterIndex argument specifies which FileFilter is the default, and the title argu- ment is text that is displayed in the title bar. If the multiSelect argument is True, the user can select multiple files, all of which are returned in an array. The following example prompts the user for a filename. It defines five file filters. Sub GetImportFileName() Dim Filt As String Dim FilterIndex As Integer Dim Title As String Dim FileName As String ‘ Set up list of file filters Filt = “Text Files (*.txt),*.txt,” & _ “Lotus Files (*.prn),*.prn,” & _ “Comma Separated Files (*.csv),*.csv,” & _ “ASCII Files (*.asc),*.asc,” & _ “All Files (*.*),*.*” ‘ Display *.* by default FilterIndex = 5 4799-2 ch12.F 6/11/01 9:32 AM Page 365 366 Part IV ✦ Working with UserForms ‘ Set the dialog box caption Title = “Select a File to Import” ‘ Get the file name FileName = Application.GetOpenFilename _ (FileFilter:=Filt, _ FilterIndex:=FilterIndex, _ Title:=Title) ‘ Exit if dialog box canceled If FileName = False Then MsgBox “No file was selected.” Exit Sub End If ‘ Display full path and name of the file MsgBox “You selected “ & FileName End Sub Figure 12-6 shows the dialog box that appears when this procedure is executed. Figure 12-6: The GetOpenFilename method displays a customizable dialog box. The following example is similar to the previous example. The difference is that the user can press Ctrl or Shift and select multiple files when the dialog box is dis- played. Notice that I check for the Cancel button click by determining if FileName is an array. If the user doesn’t click Cancel, the result is an array that consists of at least one element. In this example, a list of the selected files is displayed in a mes- sage box. 4799-2 ch12.F 6/11/01 9:32 AM Page 366 [...]... Forms toolbar These controls are insertable objects (and are compatible with Excel 5 and Excel 95) ✦ Control Toolbox toolbar These are ActiveX controls These controls are a subset of those that are available for use on UserForms These controls work only with Excel 97 and later versions, and are not compatible with Excel 5 and Excel 95 You can use the controls from either of these toolbars, but it’s important... purposes, Excel 97 and later still support Excel 5/ 95 dialog sheets The good news is that its much easier to work with UserForms, and they offer lots of new capabilities Excel makes it relatively easy to create custom dialog boxes for your applications In fact, you can duplicate the look and feel of almost all of Excel s dialog boxes This chapter provides an introduction and overview of UserForms How Excel. .. FileDialog object New Feature The FileDialog object is new to Excel 2002 Therefore, this technique will not work with earlier versions of Excel The following procedure displays a dialog box, which allows the user to select a directory The selected directory name (or Canceled) is then displayed using the MsgBox function Sub GetAFolder2() ‘ For Excel 2002 With Application.FileDialog(msoFileDialogFolderPicker)... only in English language versions of Excel For applications that will be used with other language versions of Excel, you can use the FindControl method, along with the Id property for the command See Chapter 22 for more information 4799-2 ch12.F 6/11/01 9:32 AM Page 3 75 Chapter 12 ✦ Custom Dialog Box Alternatives In the previous section, I pointed out a problem with accessing the Dialogs collection:... MsgBox “Canceled” Else MsgBox SelectedItems(1) End If End With End Sub The FileDialog object lets you specify the starting directory by specifying a value for the InitialFileName property In this case, the code uses Excel s default file path as the starting directory Displaying Excel s Built-In Dialog Boxes Code that you write in VBA can execute Excel s menu commands And, if the command leads to a dialog... above But if you only need to get a directory name, the solution will depend on which version of Excel you (and your users) have This section describes two ways to prompt for a directory The first method is more complicated but works with Excel 97 and later The second method is much easier but requires Excel 2002 Using a Windows API function to select a directory In this section, I present a function... accelerator keys Displaying and Closing UserForms In this section, I provide an overview of using VBA to work with UserForms Displaying a UserForm To display a UserForm from VBA, you create a procedure that uses the Show method of the UserForm object You cannot display a UserForm without using at least one line of VBA code If your UserForm is named UserForm1, the following procedure displays the dialog box... 371 4799-2 ch12.F 372 6/11/01 9:32 AM Page 372 Part IV ✦ Working with UserForms Figure 12-8: This dialog box was displayed with a VBA statement When the Go To dialog box is shown, the user can specify a named range or enter a cell address to go to This dialog box is the one that appears when you choose the Edit ➪ Go To command (or press F5) You can also write code to determine how the user dismissed... displays the Go To Special dialog box To display the Go To Special dialog box using VBA code, use this statement: Application.Dialogs(xlDialogSelectSpecial).Show Another potential problem is that you can’t display some “tabbed” dialog boxes correctly For example, there is no way to show the Format Cells dialog box with the tabs Rather, you can only show one tab at a time The following statement displays... ‘ For Excel 97 or later Dim Msg As String Dim UserFile As String Msg = “Please select a location for the backup.” UserFile = GetDirectory(Msg) If UserFile = “” Then MsgBox “Canceled” Else MsgBox UserFile End If End Sub Note Unfortunately, there is no easy way to specify a default or starting directory Using the FileDialog object to select a directory If users of your application all use Excel 2002, . use Excel 2002, you may prefer to use a simpler tech- nique that makes use of the FileDialog object. The FileDialog object is new to Excel 2002. Therefore, this technique will not work with. address, Excel displays an informative message and lets the user try again (see Figure 12-3). Figure 12-3: Excel s InputBox method performs validation automatically. VBA s MsgBox Function VBA s. ch12.F 6/11/01 9:32 AM Page 363 364 Part IV ✦ Working with UserForms Figure 12 -5: This message box displays text with tabs and line breaks. Excel s GetOpenFilename Method If your application needs

Ngày đăng: 14/08/2014, 02:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan