Excel 2002 Power Programming with VBA phần 6 potx

99 378 0
Excel 2002 Power Programming with VBA phần 6 potx

Đ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

456 Part IV ✦ Working with UserForms Figure 15-8: This modeless dialog box remains visible while the user continues working. Refer to Chapter 18 for additional information about events. The event-handler procedures follow: Private Sub Workbook_SheetSelectionChange _ (ByVal Sh As Object, ByVal Target As Range) Call UpdateBox End Sub Private Sub Workbook_SheetActivate(ByVal Sh As Object) Call UpdateBox End Sub These procedures call the UpdateBox procedure, which follows: Sub UpdateBox() With UserForm1 ‘ Make sure a worksheet is active If TypeName(ActiveSheet) <> “Worksheet” Then .lblFormula.Caption = “N/A” .lblNumFormat.Caption = “N/A” .lblLocked.Caption = “N/A” Exit Sub End If Cross- Reference 4799-2 ch15.F 6/11/01 9:38 AM Page 456 458 Part IV ✦ Working with UserForms Figure 15-9 shows a much more sophisticated version of this example (it’s also on the CD-ROM). This version displays quite a bit of additional information about the selected cell. Long-time Excel users may notice the similarity with the Info window — a feature that was removed from Excel several years ago. The code is too lengthy to display here, but you can view the well-commented code in the example workbook. Figure 15-9: This UserForm displays information about the active cell. Multiple Buttons, One Event-Handler Every CommandButton on a UserForm must have its own procedure to handle its Click event. For example, if you have two CommandButtons, you’ll need at least two event-handler procedures: Private Sub CommandButton1_Click() ‘ Code goes here End Sub Private Sub CommandButton2_Click() ‘ Code goes here End Sub In other words, you cannot assign a macro to execute when any CommandButton is clicked. Each Click event-handler is “hard-wired” to its CommandButton. You can, however, have each event-handler call another all-inclusive macro in the event- handler procedures, but you’ll need to pass an argument to indicate which button was clicked. In the following examples, clicking either CommandButton1 or CommandButton2 both execute the ButtonClick procedure, and the single argument tells the ButtonClick procedure which button was clicked. 4799-2 ch15.F 6/11/01 9:38 AM Page 458 459 Chapter 15 ✦ Advanced UserForm Techniques Private Sub CommandButton1_Click() Call ButtonClick(1) End Sub Private Sub CommandButton2_Click() Call ButtonClick(2) End Sub If your UserForm has many CommandButtons, setting up all of these event-handlers can get tedious. You might prefer to have a single procedure that could determine which button was clicked, and take the appropriate action. This section describes a way around this limitation by using a Class Module to define a new class. This example is available on the companion CD-ROM. Procedure The following steps describe how to re-create the example workbook: 1. Create your UserForm as usual, and add several CommandButtons (the exam- ple on the CD contains 16 CommandButttons).This example assumes the form is named UserForm1. 2. Insert a class module into your project (use Insert ➪ Class Module), give it the name BtnClass, and. enter the following code. You will need to customize the ButtonGroup_Click procedure. Public WithEvents ButtonGroup As MsForms.CommandButton Private Sub ButtonGroup_Click() Msg = “You clicked “ & ButtonGroup.Name & vbCrLf _ & vbCrLf Msg = Msg & “Caption: “ & ButtonGroup.Caption _ & vbCrLf Msg = Msg & “Left Position: “ & ButtonGroup.Left _ & vbCrLf Msg = Msg & “Top Position: “ & ButtonGroup.Top MsgBox Msg, vbInformation, ButtonGroup.Name End Sub 3. Insert a normal VBA module and enter the following code. This routine simply displays the UserForm: Sub ShowDialog() UserForm1.Show End Sub On the CD-ROM 4799-2 ch15.F 6/11/01 9:38 AM Page 459 460 Part IV ✦ Working with UserForms 4. In the code module for the UserForm, enter the code in Listing 15-4. This pro- cedure is kicked off by the UserForm’s Initialize event. Notice that the code excludes a button named OKButton from the “button group.” Therefore, clicking the OKButton does not execute the ButtonGroup_Click procedure. Listing 15-4: Establishing the Buttons() object array Dim Buttons() As New BtnClass Private Sub UserForm_Initialize() Dim ButtonCount As Integer Dim ctl As Control ‘ Create the Button objects ButtonCount = 0 For Each ctl In UserForm1.Controls If TypeName(ctl) = “CommandButton” Then If ctl.Name <> “OKButton” Then ‘Skip the OKButton ButtonCount = ButtonCount + 1 ReDim Preserve Buttons(1 To ButtonCount) Set Buttons(ButtonCount).ButtonGroup = ctl End If End If Next ctl End Sub After performing these steps, you can execute the ShowDialog procedure to dis- play the UserForm. Clicking any of the CommandButtons (except the OKButton) executes the ButtonGroup_Click procedure. Figure 15-10 shows an example of the message displayed when a button is clicked. Figure 15-10: The ButtonGroup_Click procedure describes the button that was clicked. 4799-2 ch15.F 6/11/01 9:38 AM Page 460 461 Chapter 15 ✦ Advanced UserForm Techniques Adapting this technique You can adapt this technique to work with other types of controls. You’ll need to change the type name in the Public WithEvents declaration. For example, if you have OptionButtons instead of CommandButtons, use a declaration statement like this: Public WithEvents ButtonGroup As MsForms.OptionButton A Color Picker Dialog This example is similar to the example in the previous section, but a bit more com- plex. The example workbook demonstrates a technique to display a UserForm that allows the user to select a color from the Workbook’s color palette (which consists of 56 colors). The example is actually a function (named GetAColor) that displays a UserForm and returns a color value. This example is available on the companion CD-ROM. The GetAColor function follows: Public ColorValue As Variant Dim Buttons(1 To 56) As New ColorButtonClass Function GetAColor() As Variant ‘ Displays a UserForm and returns a ‘ color value - or False if no color is selected Dim ctl As Control Dim ButtonCount As Integer ButtonCount = 0 For Each ctl In UserForm1.Controls ‘ The 56 color buttons have their ‘ ‘ Tag property set to “ColorButton” If ctl.Tag = “ColorButton” Then ButtonCount = ButtonCount + 1 Set Buttons(ButtonCount).ColorButton = ctl ‘ Get colors from the active workbook’s palette Buttons(ButtonCount).ColorButton.BackColor = _ ActiveWorkbook.Colors(ButtonCount) End If Next ctl UserForm1.Show GetAColor = ColorValue End Function On the CD-ROM 4799-2 ch15.F 6/11/01 9:38 AM Page 461 462 Part IV ✦ Working with UserForms The UserForm contains 56 CommandButton controls, which are colored using the colors in the active workbook’s palette. You can access the GetAColor function with a statement such as the following: UserColor = GetAColor() Executing this statement displays the UserForm and assigns a color value to the UserColor variable. The color corresponds to the color selected by the user. Figure 15-11 shows the UserForm (it looks better in color), which contains 56 CommandButton controls. The BackColor property of each button corresponds to one of the colors in the workbook’s color palette. Clicking a button unloads the UserForm and provides a value for the function to return. Figure 15-11: This dialog box lets the user select a color by clicking a button. The example file on the accompanying CD-ROM contains the following: ✦ A UserForm (UserForm1) that contains a dialog box with 56 CommandButtons (plus a few other accoutrements). ✦ A class module ( ColorButtonClass) that defines a ColorButton class. ✦ A VBA module ( Module1) that contains a Function procedure (GetAColor). ✦ Two examples that demonstrate the GetAColor Function procedure. The GetAColor procedure sets up the UserForm and displays it. It later returns the color value of the selected button. If the user clicks Cancel, GetAColor returns False. As the user moves the mouse pointer over the color buttons, the Color Sample image displays the color. The code behind this UserForm is rather lengthy, so it’s not listed here. You can, however, open the workbook from the CD-ROM and examine the code. 4799-2 ch15.F 6/11/01 9:38 AM Page 462 463 Chapter 15 ✦ Advanced UserForm Techniques Displaying a Chart in a UserForm With Excel 5 or Excel 95, it was very easy to display a “live” chart in a custom dialog box (using a dialog sheet): Just copy a chart and paste it into your dialog sheet. Oddly, there is no direct way to display a chart in a UserForm. You can, of course, copy the chart and paste it to the Picture property of an Image control, but this creates a static image of the chart and will not display any changes to the chart. Although UserForms are vastly superior to the old dialog sheets, this is one area that Microsoft seems to have overlooked. You can still use dialog sheets in Excel 97 or later. Therefore, you are certainly free to use a dialog sheet to display a live chart in a dialog box. This section describes two methods to display a chart in a UserForm. Method 1: Save the chart as a file Just because Microsoft doesn’t allow a live chart to be displayed in a UserForm, doesn’t mean it can’t be done! Figure 15-12 shows a UserForm with a chart dis- played in an Image object. The chart actually resides on a worksheet, and the UserForm always displays the current chart. This technique works by copying the chart to a temporary graphics file, then setting the Image control’s Picture prop- erty to the temporary file. Figure 15-12: With a bit of trickery, a UserForm can display “live” charts. General steps To display a chart in a UserForm, follow these general steps: 1. Create your chart or charts as usual. 2. Insert a UserForm and then add an Image control. Note 4799-2 ch15.F 6/11/01 9:38 AM Page 463 464 Part IV ✦ Working with UserForms 3. Write VBA code to save the chart as a GIF file, and then set the Image control’s Picture property to the GIF file. You need to use VBA’s LoadPicture function to do this. 4. Add other bells and whistles as desired. For example, the UserForm in the demo file contains controls that let you change the chart type. Alternatively, you could write code to display multiple charts. Saving a chart as a GIF file The following code demonstrates how to create a GIF file (named temp.gif) from a chart (in this case, the first chart object on the sheet named Data): Set CurrentChart = Sheets(“Data”).ChartObjects(1).Chart Fname = ThisWorkbook.Path & “\temp.gif” CurrentChart.Export FileName:=Fname, FilterName:=”GIF” When this code is executed, you’ll see a pop-up window that displays the progress. In response to a common question, I’m not aware of any way to suppress this progress display. Changing the Image control’s Picture property If the Image control on the UserForm is named Image1, the following statement loads the image (represented by the Fname variable) into the Image control: Image1.Picture = LoadPicture(Fname) This technique works fine, but you may notice a slight delay as the chart is saved and then retrieved. On a fast system, however, this delay is barely noticeable. Method 2: Use the OWC ChartSpace control As I mentioned in Chapter 13, a UserForm may contain other controls that aren’t normally included in the Toolbox. Microsoft includes the “Office Web Components” (OWC) with Office 2002, and you can use the Web Component controls in your UserForms. Figure 15-13 shows an example of a UserForm that contains a ChartSpace control. This technique does not allow you to display an existing Excel chart on a UserForm. Rather, you must write code that creates the chart in the ChartSpace control. Making the ChartSpace control available The first step is to add the ChartSpace control to your Toolbox. Right-click the tool- box to display the Additional Controls dialog box. Scroll down the list and place a check mark next to Microsoft Office Chart 10.0 (if you’re using Excel 2000, the item will be named Microsoft Office Chart 9.0). Click OK, and your Toolbox will have a new icon. Note Note 4799-2 ch15.F 6/11/01 9:38 AM Page 464 465 Chapter 15 ✦ Advanced UserForm Techniques Figure 15-13: This UserForm contains a Spreadsheet control. Adding the ChartSpace control to a UserForm Adding a ChartSpace control to your UserForm works just like any of the standard controls. When the control is added, you won’t see a chart displayed. It is, after all, just a chart space control. You’ll need to write code that creates the actual chart. Creating the chart The following code, which is located in the UserForm code module, creates a chart using data stored on a worksheet. The category labels are in A2:A13, and the chart data is in B2:B13. It assumes that the ChartSpace object is named ChartSpace1. Sub CreateChart() Dim Chart1 As ChChart ‘WCChart Dim Series1 As ChSeries ‘WCSeries Dim r As Integer Dim XValues(1 To 12) Dim DataValues(1 To 12) ‘ Add a chart to the ChartSpace Set Chart1 = ChartSpace1.Charts.Add ‘ Give it a title With Chart1 .HasTitle = True .Title.Caption = Range(“B1”) End With 4799-2 ch15.F 6/11/01 9:38 AM Page 465 [...]... with other applications, and Chapter 21 discusses the topic of add-ins A R T V ✦ ✦ ✦ ✦ In This Part Chapter 16 Developing Excel Utilities with VBA Chapter 17 Working with Pivot Tables Chapter 18 Working with Charts Chapter 19 Understanding Excel s Events Chapter 20 Interacting with Other Applications Chapter 21 Creating and Using Add-Ins ✦ ✦ ✦ ✦ 4799-2 PO5.F 6/ 11/01 9:38 AM Page 4 76 4799-2 ch 16. F 6/ 11/01... easily can be turned into utilities Using VBA to Develop Utilities When I received the beta version of Excel 5, I was blown away by VBA s potential VBA was light-years ahead of Excel s powerful XLM macro language, and it made Excel the clear leader among spreadsheets in terms of programming In an effort to learn VBA, I wrote a collection of Excel utilities using only VBA I figured that I would learn the... All work done by the Text Tools utility is performed by VBA code contained in the code module for the FormMain object The ApplyButton_Click procedure in Listing 16- 2 is executed when the user clicks the Apply button 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 487 Chapter 16 ✦ Developing Excel Utilities with VBA Listing 16- 2: Applying the chosen changes without dismissal of the dialog box Private Sub ApplyButton_Click()... Makes a Good Utility? An Excel utility, of course, should ultimately make your job easier or more efficient But if you’re developing utilities for other users, what makes an Excel utility valuable? I’ve put together a list of elements that are common to good utilities: 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 479 Chapter 16 ✦ Developing Excel Utilities with VBA ✦ It adds something to Excel This may be a new... 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 477 16 C H A P T E R Developing Excel Utilities with VBA T his chapter is about Excel utilities A utility, in general, is something that enhances software, adding useful features or making existing features more accessible As you’ll see, creating utilities for Excel is an excellent way to make a great product even better About Excel Utilities A utility isn’t an end... modifications Clicking the Help button displays a help dialog box, and clicking the Exit button dismisses the dialog box Figure 16- 1 shows an example of the Text Tools utility in use 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 481 Chapter 16 ✦ Developing Excel Utilities with VBA Figure 16- 1: Using the Text Tools utility to change text to proper case The Text Tools workbook The Text Tools workbook consists of the... FormMain It also works well with a multiple range selection I wrote the ValidContext function to be a “general-purpose” function that can be used in other applications In other words, there is nothing in the function that 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 485 Chapter 16 ✦ Developing Excel Utilities with VBA makes it specific to the Text Tools utility All of the utilities in my Power Utility Pak use this... ch15.F 466 6/ 11/01 9:38 AM Page 466 Part IV ✦ Working with UserForms For r = 2 To 13 XValues(r - 1) = Cells(r, 1) DataValues(r - 1) = Cells(r, 2) Next r ‘ Create a chart series Set Series1 = Chart1.SeriesCollection.Add ‘ Specify chart type and data With Series1 Type = chChartTypeColumnClustered SetData chDimCategories, chDataLiteral, XValues SetData chDimValues, chDataLiteral, DataValues End With End... active window: ✦ ✦ ✦ ✦ In This Chapter About Excel utilities and utilities in general Why use VBA to develop utilities What you need to know to develop good utilities Step-by-step details for developing a useful Excel utility to manipulate text in cells Where to go for more Excel utilities ✦ ✦ ✦ ✦ 4799-2 ch 16. F 478 6/ 11/01 9:39 AM Page 478 Part V ✦ Advanced Programming Techniques Sub ToggleGridDisplay()... ChangeCaseTab procedure if the MultiPage’s Value property is 0 (that is, the first page is active) Listing 16- 3 shows the complete ChangeCaseTab procedure 4799-2 ch 16. F 6/ 11/01 9:39 AM Page 489 Chapter 16 ✦ Developing Excel Utilities with VBA Listing 16- 3: Altering the case of text in cells Sub ChangeCaseTab() Dim WorkRange As Range Dim Cell As Range Dim CellCount As Long Set WorkRange = CreateWorkRange(Range(RefEdit1.Text), . ChartSpace1.Charts.Add ‘ Give it a title With Chart1 .HasTitle = True .Title.Caption = Range(“B1”) End With 4799-2 ch15.F 6/ 11/01 9:38 AM Page 465 466 Part IV ✦ Working with UserForms For r = 2 To 13 XValues(r. two versions on the CD: one for Excel 2000 (using OWC 9.0), and one for Excel 2002 (using OWC 10.0). On the CD-ROM Note 4799-2 ch15.F 6/ 11/01 9:38 AM Page 466 467 Chapter 15 ✦ Advanced UserForm. and examine the code. 4799-2 ch15.F 6/ 11/01 9:38 AM Page 462 463 Chapter 15 ✦ Advanced UserForm Techniques Displaying a Chart in a UserForm With Excel 5 or Excel 95, it was very easy to display

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