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

Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 9 ppsx

50 438 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 50
Dung lượng 1,41 MB

Nội dung

.Axes(xlCategory).MinorTickMark = xlOutside .Axes(xlValue).MinorTickMark = xlOutside ‘———————————————————————————— ‘Use Excel worksheet function to set the maximum scale on ‘the value axis. ‘———————————————————————————— .Axes(xlValue).MaximumScale = Application.WorksheetFunction. _ RoundUp(Application.WorksheetFunction. _ Max(dataRange), -1) .Axes(xlCategory).HasTitle = True .Axes(xlCategory).AxisTitle.Characters.Text = “X-axis Labels” .Axes(xlValue).HasTitle = True .Axes(xlValue).AxisTitle.Characters.Text = “Y-axis” .SeriesCollection(1).Name = “Sample Data” .SeriesCollection(1).Values = dataRange End With End Sub In the AddChartSheet() sub procedure, a specific Axis object is returned from the Axes col- lection object by passing a defined constant with the Axes() method. The Axes() method returns an Axis object and takes up to two parameters: one for the axis type (xlCategory, xlSeries, or xlValue), and another for the axis group (xlPrimary or xlSecondary). The axis type xlCategory represents the x-axis on the chart, and xlValue represents the y-axis. The axis type xlSeries applies only to 3D charts and represents the z-axis. The axis group is either xlPrimary (default) or xlSecondary (applies to charts containing multiple Series objects). The rest of the objects and properties set via the Axis object are fairly straightforward and include setting tick marks and chart labels. The upper limit of the y-axis scale is set using Excel worksheet functions that return the maximum value from the variable dataRange (defined at the beginning of the procedure) rounded up to single-digit precision. The data is finally added to the chart by setting the Values property of the Series object (returned from the SeriesCollection collection object) with the range variable dataRange. Figure 9.8 shows the components specifically added to the chart by the preceding code. The chart also contains components created from default properties of the various chart related objects. For example, the gridlines in the figure are the major gridlines on the y-axis and are displayed by default. To prevent them from being displayed, I could have added a statement such as ActiveChart.Axes(xlValue).MajorGridlines = False. 389 Chapter 9 • Excel Charts 390 Creating an Embedded Chart To add an embedded chart to a worksheet, use the Add() method of the ChartObects collec- tion object. The AddEmbeddedChart() sub procedure creates the same column chart as the AddChartSheet() sub procedure listed in the previous section; however, it embeds the chart on an existing worksheet named Embedded Charts. Public Sub AddEmbeddedChart() Dim dataRange As Range Set dataRange = Range(frmDataRange.txtDataRange.Text) frmDataRange.Hide Sheets(“Create Chart”).ChartObjects.Add Left:=200, _ Top:=50, Width:=500, Height:=350 Sheets(“Create Chart”).ChartObjects(1).Activate With ActiveChart .ChartType = xlColumnClustered .SeriesCollection.NewSeries .HasLegend = True .Legend.Position = xlRight .Axes(xlCategory).MinorTickMark = xlOutside .Axes(xlValue).MinorTickMark = xlOutside Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 9. 8 The column chart created by the AddChartSheet() sub procedure. MaximumScale ChartType = xlColumnClustered MinorTickMark = xlOutside SeriesCollection(1). Valu es HasLegend = True Legend.Position = xlRight SeriesCollection(1). Name=”Sample Data” HasTitle = True AxisTitle.Characters. Text = “X-axis Labels” .Axes(xlValue).MaximumScale = Application.WorksheetFunction.RoundUp( _ Application.WorksheetFunction.Max(dataRange), -1) .Axes(xlCategory, xlPrimary).HasTitle = True .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = _ “X-axis Labels” .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = “Y-axis” .SeriesCollection(1).Name = “Sample Data” .SeriesCollection(1).Values = dataRange End With End Sub When adding an embedded chart, the Add() method of the ChartObjects collection object accepts four parameters that define the position of the upper-left corner of the chart on the worksheet, as well as the chart width and height. The position properties of the Add() method (Left and Top) are relative to the upper-left corner of cell A1 and are in units of points. The Activate method of the ChartObject object is equivalent to selecting the chart because only one Chart object is contained in a ChartObject object. Before setting the properties of the Chart object, the chart must contain at least one Series object. Thus, the NewSeries method is used to add an empty Series object to the chart. This is another difference from adding chart sheets, where a Series object is automatically added on creation of the chart sheet. The properties of the Chart object are then set in the same manner as was done with the chart sheet. The preceding examples demonstrate only a small fraction of the objects, properties, and methods available in a Chart object. Don’t be intimidated by the breadth of the Chart object and its components! Always remember that a large problem can be broken into many smaller, more manageable problems. Once you learn how to access a chart, setting the properties of any of its component objects is basically the same. The hard part is learning what objects are available to the specific chart being manipulated. The number of component objects in a Chart object varies with the chart type (column, bar, scatter, and so on) and with the sub- category of chart type (clustered, stacked, 3D, and so on). For example, a 3D column chart has Wall, Floor, and Corners objects, but a clustered column chart does not have these objects. To learn the differences between chart types or to just learn what is available for a specific chart type, use recorded macros. First, create the chart from the Excel application then alter its appearance with the macro recorder turned on. Be careful to record only a small number of actions, say two to three at one time, because the macro recorder adds a lot of unnecessary code (setting default values). Keep in mind that as you select a component of the chart with 391 Chapter 9 • Excel Charts 392 the mouse, you are really selecting a component object of the Chart object. The dialog box that appears when the component object is double-clicked or selected from the chart menu sets the properties of that object. For example, the Format Axis dialog box shown in Figure 9.9 appears when the user double-clicks on a chart axis. Figure 9.9 shows some of the properties of the Axis object. If the macro recorder is on while these properties are altered, the VBA code used to set these properties will be recorded when OK is clicked in the dialog box. After recording a small macro, proceed to the VBA IDE to examine the recorded code. If any of the code needs clarification, select the unknown key- word and press F1 to retrieve its documentation from the online help. This is an extremely helpful tool for learning how to program specific Excel components and the advantage should be exploited. Chart Events The Chart object has several events that are triggered by various user actions. Some of the events are familiar—like Activate(), MouseDown(), and MouseUp()— but a few are unique to the Chart object. Table 9.3 summarizes the less familiar events associated with the Chart object. Chart object events are not automatically enabled with embedded charts. Although Chart object events can be enabled for embedded charts, the methods involved are beyond the scope of this book. HINT Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 9.9 The Format Axis dialog box. Chart Sheets Chart events are automatically enabled with chart sheets. To catch events triggered by the user in a chart sheet, add code to an event procedure contained in the module associated with the chart sheet. The code window can be opened in the same manner as with a worksheet. Figure 9.10 shows the code window of a chart sheet selected from the project explorer. The active project displayed in Figure 9.10 is an Excel workbook containing several chart sheets. 393 Chapter 9 • Excel Charts Event Trigger Calculate When new or changed data is charted DragOver When a range of cells is dragged over a chart DragPlot When a range of cells is dragged and dropped on a chart Resize When the chart is resized Select When a chart element is selected SeriesChange When the value of a charted data point changes TABLE 9.3 CHART O BJECT E VENTS Figure 9.10 Adding code to an event procedure of a chart sheet. Chart sheet component module Chart sheets 394 Unfortunately, some of the events unique to the Chart object cannot be used with a chart sheet because there is no manner in which the user can trigger them. For example, the user cannot drag and drop a range of cells over the chart when the data is in another worksheet; however, the other chart events work as expected, and an example using the Select() event procedure of the Chart object is listed here. Private Sub Chart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long) If ElementID = xlSeries And Arg2 > 0 Then ActiveChart.SeriesCollection(Arg1).Points(Arg2).ApplyDataLabels Type:=xlShowValue End If End Sub The Select() event procedure of the Chart object accepts three parameters: ElementID is a long integer that refers to the component object selected by the user ( ChartArea, PlotArea, Series, and so on), and Arg1 and Arg2 are long integers that refer to specific components of the selected object; thus, the meaning of Arg1 and Arg2 depends on the object selected by the user. The definitions of Arg1 and Arg2 for some of the more common chart components are listed in Table 9.4. The preceding Select() event procedure is triggered when the user selects a chart component. If that component is a single data point on the chart then Arg1 holds the index value of the selected Series object (representing a series of values) and Arg2 holds the index value of the selected Point object (representing the individual values in the series). Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition ElementID Arg1 Arg2 xlAxis, xlAxisTitle, xlDisplayUnitLabel, xlMajorGridlines, xlMinorGridlines Axis Index Axis Type xlChartArea, xlChartTitle, xlCorners, xlDataTable, xlLegend, xlPlotArea None None xlDataLabel, xlSeries Series Index Point Index xlErrorBars, xlLegendEntry, xlLegendKey Series Index None xlTrendline Series Index TrendLine Index xlXErrorBars, xlYErrorBars Series Index None TABLE 9.4 ARGUMENT D EFINITIONS FOR THE S ELECT() E VENT OF THE C HART OBJECT The purpose of the code entered in the Select() event procedure is to add a label to any point in a data series selected by the user. To accomplish this, the parameter ElementID is tested for equivalence to three (VBA-defined constant xlSeries, see online help for addi- tional constants) because that’s the value that represents a Series object. If the user has selected a single point in a data series, the selected point is labeled with its value by using the ApplyDataLabels() method of the Point object and setting the Type argument to the con- stant xlShowValue. In this example, Arg2 holds the value –1 if the entire series is selected and will not hold a meaningful value until the user selects an individual point from the data series. When the user does select an individual data point, the value of Arg2 is passed to the Points() method, which returns a Point object from the Points collection object. In this case, the Points() method returns the specific data point selected by the user. Consider the chart shown in Figure 9.11 where two data series are plotted in a scatter chart. The chart is contained in a chart sheet and the Select() event procedure of the Chart object contains the previously listed code. If the user selects Series 1 with a single click of the mouse, the Select() event procedure is triggered but the parameters passed to the procedure are ElementID=3, Arg1=1, and Arg2=-1; so the conditional expression in the If/Then statement is false; therefore, no label is added to the chart. With Series 1 selected, the user then clicks on the 6th data point in Series 1. Again, the Select() event procedure is triggered, but this time the parameters passed to it are ElementID=3, Arg1=1, and Arg2=6. This time, the condi- tional in the If/Then statement is true and the label 54 is added to the chart. 395 Chapter 9 • Excel Charts Figure 9.11 Detecting a user selection with the Select() event of the Chart object. Data label 396 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Before writing the code for the Select() event procedure, I recorded a macro while adding a label to a charted point. This reminded me how to add the label to individual data points using VBA. To learn how to use the Select() event procedure of the Chart object, I added the statement Debug.Print ElementID; Arg1; Arg2 to the procedure and watched the Immediate window while I clicked on various components of the Chart object. Chapter Project: The Alienated Game The Alienated Game uses a chart sheet for the user interface (see Figure 9.12) and illustrates the use of several VBA objects subordinate to the Chart object. The program uses the less common bubble chart type because the data markers (represented by Point objects in VBA) in a regular scatter chart cannot hold images. A total of ten data series with ten values each are charted and their markers are randomly filled with one of seven images. The object of the game is to swap two images such that it will create a sequence of three or more identical images in a column or row (hereafter referred to as a score sequence). When a score sequence is created, their images are removed from the chart and the images above the score sequence are moved down. Finally, the empty markers at the top of the chart are randomly filled with new images. The player scores ten points for each image removed and the game ends when all possible moves are exhausted. HINT Figure 9.12 The Alienated Game. Requirements for the Alienated Game From the user’s point of view, the Alienated Game is quite simple because all they have to do is select data markers on a chart. From your point of view, I’m betting the game is more of a challenge; especially if you’re not that comfortable with charts. If your comfort level is low, that provides all the more reason to spend ample time planning the program. The following list contains my requirements for the Alienated Game. 1. The game interface shall consist of a bubble chart created on a chart sheet. 2. The chart’s data point markers shall display 100 images in a 10 by 10 grid. 3. Each image displayed in a data marker shall be randomly chosen from one of seven images. 4. The program shall be initiated from a form button placed on the chart. 5. The program shall track the user’s score and display it via a chart title. 6. The program shall display help messages to the user via a chart title. 7. When a new game begins, all data markers in the chart shall be updated with new images. 8. Any time new images are added to the chart, the program shall scan the chart for a score sequence. 9. When a score sequence is found, the program shall record the score (10 pts per image), remove the images, move images above the score sequence down to fill the vacancies, and add new images to the top of the chart. 10. When the user selects two images for swapping, the program shall validate the selection before swapping the images. Selections are valid if they are adjacent and non-diagonal and they must generate at least one score sequence. Valid selections are swapped and the chart is scanned in order to process the score sequence. 11. The source data for the chart shall be added programmatically when a new game begins and the chart is initialized. The source data shall remain static. 12. The images displayed in the chart’s data markers shall be mapped to the values in a range of 100 cells in a hidden worksheet. Changes made to the chart during the course of a game shall be a result of changes made to these mapped values. Designing the Alienated Game My goal for this project is to illustrate how to program with Excel’s Chart object model, so its interface must take advantage of an Excel chart. This makes the project unusual with 397 Chapter 9 • Excel Charts 398 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition respect to everything you’ve seen thus far because the game’s interface will not involve a worksheet or VBA form. Nevertheless, charts are constructed in order to display data that is typically stored in a worksheet; so the game will still require many of the common Excel objects you have seen in other projects. The Chart Sheet Interface This chapter teaches you how to program Excel’s Chart object so the interface for the project is built from a chart. Specifically, a chart sheet consisting of a bubble chart will serve to dis- play the images. The requirements state that the game must involve a 10 by 10 grid of 100 images. To satisfy this requirement I will create the chart from ten data sets consisting of ten x,y-value pairs. The data is charted as ten different series in the chart. Each data set must use the same set of values for the x-axis variable to ensure vertical alignment of the images (for example, if x=2 for one element in each series, then their corresponding data markers are vertically aligned across the y-axis). In addition, the values for the x-axis variable must have a uniform increment for homogeneous spacing of the images. To ensure the images are aligned hori- zontally the y-values must be equivalent within a data series (for example, if y=2 for every element in a series, then the corresponding data markers are aligned horizontally across the x-axis), and the difference in the y-values between data series must also be uniform. The magnitude of the numbers doesn’t really matter since the data is static, but I will keep it simple and use 0-9 for the x-axis variable, and 0-9 for the y-axis series (that is, the first y-axis data series is all 0’s, the second is all 1’s, and so on). The third variable in a bubble chart is expressed by the size of the data marker. I don’t need this variable, but I need it to be iden- tical for all data points such that the images are uniform in size. Figure 9.13 shows the chart sheet interface for the Alienated Game and how the chart sheet appears before any images are added to the data markers. Note that I formatted the chart to include a background image simulating a starry night sky. As can be seen in Figure 9.13 a new game is started from the click of a button. The button must come from the Forms toolbar because you cannot place ActiveX controls on a chart sheet. The button is assigned to a public VBA procedure that initializes the chart with new images and clears the score so a new game can begin. Displaying the score and help messages to the user is a bit more difficult than usual. In pre- vious projects, I have used merged cells or Label controls to display text, but neither of these options is available with a chart sheet. The best way to display text on a chart is to use the axis and chart titles—that’s what you see in Figure 9.13. [...]... variable of the columns or rows (see ScanImages() function procedure) in the image map Nested For/ Each loops iterate through the rows or columns in the image map searching for score sequences 412 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition When a sequence is found, the last cell in the range is assigned to the cellRange component of the variable array endPts and the number... the map shown in Figure 9. 17 where I have emphasized the ranges that the program must score 410 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 9. 17 A sample map showing the image types contained in the bubble chart for the Alienated Game When this image map is scanned, the array variable endPointsRow will be dimensioned with three elements The cellRange components... Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Program Outline When playing a game, the Alienated Game should proceed as outlined in the following: 1 The user initiates a new game with a click of the form button drawn on the chart sheet interface 2 The chart sheet and ImageMap worksheet containing the image map are initialized for a new game 3 The data is added to the chart... chAlien.SeriesCollection For I = 0 To UBound(mapRange) For Each c In mapRange(I) chSeriesCol.Item(c.Row - 1).Points(c.Column - 1) _ Interior.ColorIndex = xlNone Next Next I End Sub Figure 9. 18 shows the bubble chart after the ranges shown in Figure 9. 17 have been used to remove scored images 416 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 9. 18 The bubble chart in the Alienated... cells in the range 418 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition When an empty cell is discovered, a nested For/ Each loop iterates through all cells in the column, collecting values from non-empty cells For example, if a column contains two empty cells, then the array variable colVals will end up with eight elements Immediately following the For/ Each loop a For/ Next... chart sheet and the program requires the Select() event of the Chart object, I have entered all of the program code in the module for the chart sheet Module level declarations include a string for holding the path to the image files, integers for holding the series and point numbers for the two images selected by the user, and a custom Chapter 9 • Excel Charts 403 data type defining the type DataPoints... into the data marker The ChartFillFormat object is returned by the Fill property of the Point object The specific image is selected using the value of the cell in the ImageMap worksheet mapped to the specific Point object in the chart (recall how the file names for the alien images were named, see Figure 9. 14) If the image map does not contain a value, then the ColorIndex property of the Interior object... altering the charted values, but that seems too complicated Since the bubble chart will constantly have to display 100 images in a 10 by 10 grid, it will be a lot easier if the data remains static and all the program changes are the images contained in the data markers 400 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition There are a number of methods you could use to track the. .. Sheet The public sub procedure Main() is triggered from the form button on the chart sheet and contains calls to the initialization procedures for the chart sheet, then scans the chart for score sequences Screen updating is initially turned off otherwise Excel will update the screen as images are added or removed from the chart Screen updating is turned back on so that the user can see the chart before...Chapter 9 • Excel Charts 399 Figure 9. 13 The Alienated Game chart sheet interface prior to filling the markers with images HIN T For a more advanced version of the Alienated Game, check out the Alienated_ Embedded.xls project on the Book’s CD-ROM This version of the game uses an embedded chart for the user interface; so a class module is required to enable the event procedures of the Chart object . be enabled for embedded charts, the methods involved are beyond the scope of this book. HINT Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 9. 9 The Format Axis dialog. makes the project unusual with 397 Chapter 9 • Excel Charts 398 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition respect to everything you’ve seen thus far because the. Programming for the Absolute Beginner, Second Edition Figure 9. 14 The images of the aliens and their associated file names used in the Alienated Game. 401 Chapter 9 • Excel Charts Figure 9. 15 The sample

Ngày đăng: 12/08/2014, 16:21

TỪ KHÓA LIÊN QUAN