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

Excel 2002 Power Programming with VBA phần 7 pps

99 261 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 99
Dung lượng 0,97 MB

Nội dung

555 Chapter 18 ✦ Working with Charts Case xlXErrorBars: Id = “XErrorBars” Case xlYErrorBars: Id = “YErrorBars” Case xlLegendEntry: Id = “LegendEntry” Case xlLegendKey: Id = “LegendKey” Case xlAxis: Id = “Axis” Case xlMajorGridlines: Id = “MajorGridlines” Case xlMinorGridlines: Id = “MinorGridlines” Case xlAxisTitle: Id = “AxisTitle” Case xlUpBars: Id = “UpBars” Case xlDownBars: Id = “DownBars” Case xlSeriesLines: Id = “SeriesLines” Case xlHiLoLines: Id = “HiLoLines” Case xlDropLines: Id = “DropLines” Case xlRadarAxisLabels: Id = “RadarAxisLabels” Case xlShape: Id = “Shape” Case xlNothing: Id = “Nothing” Case Else: Id = “Some unknown thing” End Select MsgBox “Selection type:” & Id End Sub This procedure displays a message box that contains a description of the selected item. When the Select event occurs, the ElementID argument contains an integer that corresponds to what was selected. The Arg1 and Arg2 arguments provide additional information about the selected item (see the online help for details). The Select Case structure converts the built-in constants to descriptive strings. Enabling events for an embedded chart As I noted in the previous section, Chart events are automatically enabled for chart sheets, but not for charts embedded in a worksheet. To use events with an embed- ded chart, you need to perform the following steps: Create a class module In the VB Editor window, select your project in the Project window and select Insert ➪ Class Module. This will add a new (empty) class module to your project. If you like, you can use the Properties window to give the class module a more descriptive name. Declare a public Chart object The next step is to declare a Public variable that will be used as the class name. The variable should be of type Chart, and it must be declared in the class module using the WithEvents keyword. If you omit the WithEvents keyword, the object will not respond to events. Following is an example of such a declaration: Public WithEvents myChartClass As Chart 4799-2 ch18.F 6/11/01 9:40 AM Page 555 556 Part V ✦ Advanced Programming Techniques Connect the declared object with your chart Before your event-handler procedures will run, you must connect the declared object in the class module with your embedded chart. You do this by declaring an object of type Class1 (or whatever your class module is named). This should be a module-level object variable, declared in a regular VBA module (not in the class module). Here’s an example: Dim MyChart As New MyChartClass Then you must write code to actually instantiate the object, such as this instruction: Set myChart.myChartClass = ActiveSheet.ChartObjects(1).Chart After the preceding statement is executed, the myChartClass object in the class module points to the first embedded chart on the active sheet. Consequently, the event-handler procedures in the class module will execute when the events occur. Write event-handler procedures for the chart class In this section, I describe how to write event-handler procedures in the class mod- ule. Recall that the class module must contain a declaration such as: Public WithEvents myChartClass As Chart After this new object has been declared using the WithEvents keyword, it appears in the Object drop-down list box in the class module. When you select the new object in the Object box, the valid events for that object are listed in the Procedure drop-down box on the right (see Figure 18-16). Figure 18-16: The Procedure list displays valid events for the new Chart object. 4799-2 ch18.F 6/11/01 9:40 AM Page 556 557 Chapter 18 ✦ Working with Charts The following example is a simple event-handler procedure that is executed when the embedded chart is activated. This procedure simply pops up a message box that displays the name of the Chart object’s parent (which is a ChartObject object). Private Sub myChartClass_Activate() MsgBox myChartClass.Parent.Name & “ was activated!” End Sub The companion CD-ROM contains a workbook that demonstrates the concepts described in this section. Example: Using Chart events with an embedded chart The example in this section provides a practical demonstration of the information presented in the previous section. The example shown in Figure 18-17 consists of an embedded chart that functions as a clickable image map. Clicking one of the chart columns activates a worksheet that shows detailed data for the region. Figure 18-17: This chart serves as a clickable image map. The workbook is set up with four worksheets. The sheet named Main contains the embedded chart. The other sheets are named North, South, and West. Formulas in B1:B4 sum the data in the respective sheets, and this summary data is plotted in the chart. Clicking a column in the chart triggers an event, and the event-handler procedure activates the appropriate sheet so the user can view the details for the desired region. On the CD-ROM 4799-2 ch18.F 6/11/01 9:40 AM Page 557 558 Part V ✦ Advanced Programming Techniques The workbook contains a class module named EmbChartClass, and also a normal VBA module named Module1. For demonstration purposes, the Main worksheet also contains two buttons: One executes a procedure named EnableChartEvents, the other executes a procedure named DisableChartEvents (both are located in Module1). In addition, each of the other worksheets contains a button that exe- cutes the ReturntoMain macro that reactivates the Main sheet. The complete listing of Module1 follows: Dim SummaryChart As New EmbChartClass Sub EnableChartEvents() ‘ Called by worksheet button Range(“A1”).Select Set SummaryChart.myChartClass = _ Worksheets(1).ChartObjects(1).Chart End Sub Sub DisableChartEvents() ‘ Called by worksheet button Set SummaryChart.myChartClass = Nothing Range(“A1”).Select End Sub Sub ReturnToMain() ‘ Called by worksheet button Sheets(“Main”).Activate End Sub The first instruction declares a new object variable SummaryChart to be of type EmbChartClass — which, as you recall, is the name of the class module. When the user clicks the Enable Chart Events button, the embedded chart is assigned to the SummaryChart object, which, in effect, enables the events for the chart. Listing 18-4 shows the class module for EmbChartClass. Clicking the chart generates a MouseDown event, which executes the myChartClass_MouseDown procedure. This procedure uses the GetChartElement method to determine what element of the chart was clicked. The GetChartElement method returns information about the chart element at specified X and Y coordi- nates (information that is available via the arguments for the myChartClass_MouseDown procedure. Listing 18-4: Reacting to which column has been clicked on Public WithEvents myChartClass As Chart Private Sub myChartClass_MouseDown(ByVal Button As Long, _ ByVal Shift As Long, ByVal X As Long, ByVal Y As Long) 4799-2 ch18.F 6/11/01 9:40 AM Page 558 559 Chapter 18 ✦ Working with Charts Dim IDnum As Long Dim a As Long, b As Long ‘ The next statement returns values for ‘ IDNum, a, and b myChartClass.GetChartElement X, Y, IDnum, a, b ‘ Was a series clicked? If IDnum = xlSeries Then Select Case b Case 1 Sheets(“North”).Activate Case 2 Sheets(“South”).Activate Case 3 Sheets(“West”).Activate End Select End If Range(“A1”).Select End Sub This workbook is available on the companion CD-ROM. Charting Tricks I conclude this chapter by sharing a few charting tricks that I’ve discovered over the years. Some of these techniques may be useful in your applications, and others are simply for fun. At the very least, studying them may give you some new insights into the object model for charts. Printing embedded charts on a full page When an embedded chart is selected, you can print the chart by choosing File ➪ Print. The embedded chart will be printed on a full page by itself (just as if it were on a chart sheet), yet it will remain an embedded chart. The following macro prints all embedded charts on the active sheet, and each chart is printed on a full page: Sub PrintEmbeddedCharts() For Each chtObj In ActiveSheet.ChartObjects chtObj.Chart.Print Next chtObj End Sub On the CD-ROM 4799-2 ch18.F 6/11/01 9:40 AM Page 559 560 Part V ✦ Advanced Programming Techniques Creating a “dead chart” Normally, an Excel chart uses data stored in a range. Change the data in the range, and the chart is updated automatically. In some cases, you may want to “unlink” the chart from its data ranges and produce a “dead chart” (a chart that never changes). For example, if you plot data generated by various what-if scenarios, you may want to save a chart that represents some baseline so you can compare it with other scenarios. There are two ways to create such a chart: ✦ Paste it as a picture. Activate the chart and choose Edit ➪ Copy. Then press the Shift key and select Edit ➪ Paste Picture (the Paste Picture command is avail- able only if you press Shift when you select the Edit menu). The result will be a picture of the copied chart. ✦ Convert the range references to arrays. Click on a chart series and then click the formula bar. Press F9 to convert the ranges to an array. Repeat this for each series in the chart. The xl8galry.xls file uses this technique. This file is a special workbook used by Excel to store its custom chart formats. If you open this workbook, you’ll find 20 chart sheets. Each chart sheet has “dummy” data, which uses an array rather than a range as its source. Another way to create a dead chart is to use VBA to assign an array rather than a range to the XValues or Values properties of the Series object. Controlling a data series by hiding data Figure 18-18 shows a chart that displays daily data for 365 days. What if you only want to plot, say, the data for February? You could, of course, redefine the chart’s data range. Or, you could take advantage of Excel’s AutoFilter command. By default, a chart does not display data that’s hidden. Since Excel’s AutoFilter feature works by hiding rows that don’t meet your criteria, it’s a simple solution. Select Data ➪ Filter➪AutoFilter to turn on the AutoFilter mode. Each row heading in the filtered list displays a drop-down arrow. Click the arrow and select Custom from the list. Then enter filter criteria that will select the dates that you want to plot. The setting shown in Figure 18-19, for example, hides all rows except those that have a date in February. Note 4799-2 ch18.F 6/11/01 9:40 AM Page 560 561 Chapter 18 ✦ Working with Charts Figure 18-18: You can use Excel’s AutoFilter feature to plot only a subset of the data. This workbook is available on the companion CD-ROM. Figure 18-19: Use the Custom AutoFilter dialog box to filter a list. The resulting chart is shown in Figure 18-20. On the CD-ROM 4799-2 ch18.F 6/11/01 9:40 AM Page 561 562 Part V ✦ Advanced Programming Techniques Figure 18-20: Only visible cells are displayed in a chart. If this technique doesn’t seem to be working, you need to change a setting for the chart. Activate the chart, then choose Tools➪ Options. In the Options dialog box, click the Chart tab and place a check mark next to Plot visible cells only. Also, to ensure that the chart doesn’t disappear when its rows are hidden, set its position- ing to Don’t move or size with cells. Use the Format➪ Selected Chart Area com- mand to change this setting. Storing multiple charts on a chart sheet Most Excel users who take the time to think about it would agree that a chart sheet holds a single chart. Most of the time, that’s a true statement. However, it’s cer- tainly possible to store multiple charts on a single chart sheet. In fact, Excel lets you do this directly. If you activate an embedded chart and then select Chart ➪ Location, Excel displays its Chart Location dialog box. If you select the As new sheet option and specify an existing chart sheet as the location, the chart will appear on top of the chart in the chart sheet. Most of the time, you’ll want to add embedded charts to an empty chart sheet. To create an empty chart sheet, select a single blank cell and press F11. One advantage of storing multiple charts on a chart sheet is that you can take advantage of the View➪ Sized with Window command to automatically scale the charts to the window size and dimensions. Figure 18-21 shows an example of a chart sheet that contains six embedded charts. Note 4799-2 ch18.F 6/11/01 9:40 AM Page 562 563 Chapter 18 ✦ Working with Charts Figure 18-21: This chart sheet contains six embedded charts. This workbook is available on the companion CD-ROM. Using linked pictures in a chart Excel has a feature that lets you display a data table inside of a chart. You can select this option in Step 3 of the ChartWizard. The data table option displays a table that shows the values used in a chart. This is a handy feature, but it’s not very flexible. For example, your formatting options are limited, and you have no control over the position of the data table (it always appears below the chart). An alternative to the data table is to use a linked picture of a range. Figure 18-22 shows an example. On the CD-ROM 4799-2 ch18.F 6/11/01 9:40 AM Page 563 564 Part V ✦ Advanced Programming Techniques Figure 18-22: This chart contains a linked picture of a range used in the chart. To create a linked picture in a chart, first create the chart as you normally would. Then: 1. Select the range that you would like to include in the chart. 2. Select Edit ➪ Copy. 3. Activate the chart. 4. Press Shift, and then select Edit ➪ Paste Picture. This pastes an unlinked pic- ture of the range. 5. To create the link, select the picture and then type a reference to the range in the formula bar. The easiest way to do this is to type an equals sign, and then reselect the range. The picture now contains a live link to the range. If you change the values or cell formatting, they will be reflected in the linked picture. This workbook is available on the companion CD-ROM. On the CD-ROM 4799-2 ch18.F 6/11/01 9:40 AM Page 564 [...]... Boolean 479 9-2 ch19.F 6/11/01 9:40 AM Page 575 Chapter 19 ✦ Understanding Excel s Events Programming Events in Older Versions of Excel Versions of Excel prior to Office 97 also supported events, but the programming techniques required to take advantage of those were quite different from those described in this chapter For example, if you have a procedure named Auto_Open stored in a regular VBA module,... previews a worksheet 577 479 9-2 ch19.F 578 6/11/01 9:40 AM Page 578 Part V ✦ Advanced Programming Techniques Figure 19-3: You can cancel the print operation by changing the Cancel argument Unfortunately, Excel does not provide a sheet-level BeforePrint event Therefore, your code cannot determine what is about to be printed Workbook-Level Events Workbook-level events are events that occur within a particular... lines 569 479 9-2 ch18.F 570 6/11/01 9:40 AM Page 570 Part V ✦ Advanced Programming Techniques Summary In this chapter, I introduced the object model for charts, and showed how to write VBA code to create and manipulate charts This chapter included several examples that made use of events In the next chapter, I cover the concept of events in detail ✦ ✦ ✦ 479 9-2 ch19.F 6/11/01 9:40 AM Page 571 19 C H... UserForm events Using Application events to monitor all open workbooks Examples of processing timebased events and keystroke events ✦ ✦ ✦ ✦ 479 9-2 ch19.F 572 6/11/01 9:40 AM Page 572 Part V ✦ Advanced Programming Techniques Event Types That Excel Can Monitor Excel is programmed to monitor many different events that occur These events may be classified as the following: ✦ Workbook events Events that... such as: Sheets(“Sheet1”).OnEntry = “ValidateEntry” This statement instructs Excel to execute the procedure named ValidateEntry whenever data is entered into a cell With Excel 97 and later, you simply create a procedure named Worksheet_Change and store it in the code module for the Sheet1 object For compatibility reasons, Excel 97 and later versions still support the older event mechanism (although they... “Validating data entry,” later in this chapter Caution Disabling events in Excel applies to all workbooks For example, if you disable events in your procedure and then open another workbook that has, say, a Workbook_Open procedure, that procedure will not execute 575 479 9-2 ch19.F 576 6/11/01 9:40 AM Page 576 Part V ✦ Advanced Programming Techniques Entering event-handler code Every event-handler procedure... components has its own code module: ✦ Sheet objects (for example, Sheet1, Sheet2, and so on) ✦ Chart objects (that is, chart sheets) ✦ ThisWorkbook object 573 479 9-2 ch19.F 574 6/11/01 9:40 AM Page 574 Part V ✦ Advanced Programming Techniques ✦ General VBA modules You never put event-handler procedures in a general (that is, nonobject) module ✦ Class modules Even though the event-handler procedure must... Figure 19-5: The Worksheet_Change procedure appends the comment with each cell change 5 87 479 9-2 ch19.F 588 6/11/01 9:40 AM Page 588 Part V ✦ Advanced Programming Techniques On the CD-ROM This example is available on the companion CD-ROM Private Sub Worksheet_Change(ByVal Target As Excel. Range) If CheckBox1 Then For Each cell In Target With cell On Error Resume Next OldText = Comment.Text If Err ... are calculated in VBA and transferred directly to the Values and XValues properties of the chart’s Series object 479 9-2 ch18.F 6/11/01 9:40 AM Page 569 Chapter 18 ✦ Working with Charts Drawing with an XY chart The final example has absolutely no practical value, but you may find it interesting and maybe even a bit entertaining The worksheet consists of an embedded XY chart, along with a number of... stored in a regular VBA module, this procedure will be executed when the workbook is opened Beginning with Excel 97, the Auto_Open procedure is supplemented by the Workbook_Open event-handler procedure, stored in the code module for the ThisWorkbook object, and executed prior to Auto_Open Before Excel 97, it was often necessary to explicitly set up events For example, if you needed to execute a procedure . time- based events and keystroke events ✦✦✦✦ 479 9-2 ch19.F 6/11/01 9:40 AM Page 571 572 Part V ✦ Advanced Programming Techniques Event Types That Excel Can Monitor Excel is programmed to monitor many different. (that is, chart sheets). ✦ ThisWorkbook object. Note 479 9-2 ch19.F 6/11/01 9:40 AM Page 573 574 Part V ✦ Advanced Programming Techniques ✦ General VBA modules. You never put event-handler procedures. calculated in VBA and transferred directly to the Values and XValues properties of the chart’s Series object. 479 9-2 ch18.F 6/11/01 9:40 AM Page 568 569 Chapter 18 ✦ Working with Charts Drawing with an

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

TỪ KHÓA LIÊN QUAN