Mastering Excel 2003 Programming with VBA phần 5 doc

61 301 0
Mastering Excel 2003 Programming with VBA phần 5 doc

Đ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

4281book.fm Page 225 Sunday, February 29, 2004 5:12 PM 225 CHART MANIPULATION With chrt ' use chart wizard to populate/format empty chart .ChartWizard _ Source:=rgChartData, _ Gallery:=xlColumn, _ Format:=1, _ PlotBy:=xlColumns, _ CategoryLabels:=1, _ SeriesLabels:=1, _ HasLegend:=True, _ Title:="Gross Domestic Product Version I", _ CategoryTitle:="Year", _ ValueTitle:="GDP in billions of $" End With Set chrt = Nothing Set rgChartData = Nothing Set ws = Nothing End Sub You probably already know this, but a chart can assume two forms: it can be created as a chart sheet or it can be embedded within a worksheet. One thing that is kind of odd regarding the process of creating a chart is that you don’t have any control over what kind of chart is created when you use Charts.Add. This statement creates an empty chart sheet. This is fine and dandy if you want a chart sheet, but what if you want to embed it into a worksheet? That is what the Location method is for. YourChartObject.Location([Where], [Name]) The Where parameter can be either xlLocationNewSheet (creates a chart sheet), xlLocationAsObject (embeds in a worksheet), or xlLocationAutomatic. The Name parameter is the name of the new chart sheet if you use xlLocationNewSheet. If you use xlLocationAsObject, the Name parameter should be the name of the worksheet in which you want to embed the chart. Another somewhat peculiar aspect of creating a chart is that Location creates a new Chart object from a programmatic perspective. If you are using a Chart object variable to refer to a chart, you need to reset it when you use Location. That’s the reason for the following statement in the CreateExampleChartVersionI procedure. ' embed chart in worksheet - this creates a new object Set chrt = chrt.Location(xlLocationAsObject, ws.Name) Now that you have the chart where you want it, it is time to employ the ChartWizard method to give the chart some personality. As you can see in this example, the ChartWizard method has a lot of parameters and you’ll probably use most of them. Note, however, that all of the parameters are optional. YourChartObject.ChartWizard [Source], [Gallery], [Format], _ [PlotBy], [CategoryLabels], [SeriesLabels], [HasLegend], _ [Title], [CategoryTitle], [ValueTitle], [ExtraTitle] 4281book.fm Page 226 Sunday, February 29, 2004 5:12 PM 226 CHAPTER 10 EXPLORING OTHER EXCEL OBJECTS The parameters of the ChartWizard method are detailed in the following list. Source This is an optional parameter that represents the range that contains the source data for the chart. Gallery Gallery is the type of chart to create. Choose from xlArea, xlBar, xlColumn, xlLine, xlPie, xlRadar, xlXYScatter, xlCombination, xl3DArea, xl3DBar, xl3DColumn, xl3DLine, xl3DPie, xl3DSurface, xlDoughnut, or xlDefaultAutoFormat. Format The option number for the type of chart you specified using Gallery. This can be a num- ber from 1 through 10 depending on the type of chart. PlotBy Use xlRows or xlColumns to specify how the data is oriented. CategoryLabels Use this parameter to indicate the number of rows or columns in the source data range that consist of category labels. SeriesLabels Use this parameter to indicate the number of rows of columns in the source data range that contain series labels. HasLegend HasLegend should be true to include a legend, false to exclude it. Title The title of the chart can be specified with this parameter. CategoryTitle The category axis title. ValueTitle The value axis title. ExtraTitle The series title for 3-D charts or the second value axis title for 2-D charts. Figure 10.16 shows an example of a chart created using the ChartWizard method. This chart was generated using the CreateExampleChartVersion1 procedure from Listing 10.9. Figure 10.16 This is the chart cre- ated by Listing 10.9. 4281book.fm Page 227 Sunday, February 29, 2004 5:12 PM 227 CHART MANIPULATION You don’t necessarily need to use the ChartWizard method to create your chart. Well, technically the ChartWizard doesn’t create the chart, but it certainly does all of the heavy lifting. Another way to achieve the same result is to do it yourself using other properties and methods of the Chart object. Take a look at Listing 10.10. Listing 10.10: Creating a Chart Using the Chart Object ' creates a chart using basic Chart properties and methods Sub CreateExampleChartVersionII() Dim ws As Worksheet Dim rgChartData As Range Dim chrt As Chart Set ws = ThisWorkbook.Worksheets("Basic Chart") Set rgChartData = ws.Range("B1").CurrentRegion ' create a new empty chart Set chrt = Charts.Add ' embed chart in worksheet—this creates a new object Set chrt = chrt.Location(xlLocationAsObject, ws.Name) With chrt .SetSourceData rgChartData, xlColumns .HasTitle = True .ChartTitle.Caption = "Gross Domestic Product Version II" .ChartType = xlColumnClustered With .Axes(xlCategory) .HasTitle = True .AxisTitle.Caption = "Year" End With With .Axes(xlValue) .HasTitle = True .AxisTitle.Caption = "GDP in billions of $" End With End With Set chrt = Nothing Set rgChartData = Nothing Set ws = Nothing End Sub 4281book.fm Page 228 Sunday, February 29, 2004 5:12 PM 228 CHAPTER 10 EXPLORING OTHER EXCEL OBJECTS As you can see in Figure 10.17, this listing produces the same result as Listing 10.9. Personally, I prefer this listing over the ChartWizard method. You have more flexibility doing it manually as we do here, and I think it’s easier to read and understand. Figure 10.17 An exact match. This is the chart produced by Listing 10.10. Chart Hunting As you know, a chart can take up residence in two locations: as a chart sheet in the workbook, or as an embedded chart on a worksheet. Setting a reference to an existing chart varies according to what kind of location the chart lives in. For chart sheets, you can refer to them almost like a worksheet as the following code snippet demonstrates. Dim chrt1 As Chart Dim chrt2 As Chart ' set a reference to the chart sheet named Chart4 Set chrt1 = ThisWorkbook.Charts("Chart4") ' set a reference to the 2nd chart sheet in the wb Set chrt2 = ThisWorkbook.Charts(2) If your chart is embedded in a worksheet, however, you need to go through the ChartObjects col- lection, which is a property of the Worksheet object that contains the embedded chart. An example of this method is shown in the following snippet. Dim chrt1 As Chart Dim chrt2 As Chart 4281book.fm Page 229 Sunday, February 29, 2004 5:12 PM 229 CHART MANIPULATION Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets(1) ' set a reference to the embedded chart named Chart4 Set chrt1 = ws.ChartObjects("Chart4").Chart ' set a reference to the 2nd embedded chart Set chrt2 = ws.ChartObjects(2).Chart Notice that to get to the actual chart object you need to locate a specific ChartObject first. You can think of a ChartObject as a special object that exists merely to contain a chart on a worksheet. Much like a flea needs a dog, a Chart needs a ChartObject to reside on a worksheet. You can apply all of the techniques you learned about looking for specific worksheets in a work- book to looking for chart sheets. Looking for embedded charts is another story due to two minor complications. First, it isn’t practical to know the index order of the chart objects on a worksheet. If you only have one chart on a worksheet, you’re fine (but who’s to say that another chart doesn’t get added unbeknownst to you?). Second, unless you named the chart when you created it, you can’t refer to it by name. What to do? Simple, create a procedure that returns a chart based on some identifying character- istic. For example, you could retrieve charts according to the chart title, one of the axis titles, the source data range, or any of the other identifying characteristics. Listing 10.11 presents an example of a procedure that searches for and returns a chart based on a chart title. Listing 10.11: Seaching for Charts Using the Chart Title ' searches charts on a worksheet by chart title Function GetChartByCaption(ws As Worksheet, sCaption As String) _ As Chart Dim chtObj As ChartObject Dim cht As Chart Dim sTitle As String Set cht = Nothing ' loop through all chart objects on the ws For Each chtObj In ws.ChartObjects ' make sure current chart object chart has a title If chtObj.Chart.HasTitle Then sTitle = chtObj.Chart.ChartTitle.Caption ' is this title a match? If StrComp(sTitle, sCaption, vbTextCompare) = 0 Then 4281book.fm Page 230 Sunday, February 29, 2004 5:12 PM 230 CHAPTER 10 EXPLORING OTHER EXCEL OBJECTS ' bingo Set cht = chtObj.Chart Exit For End If End If Next Set GetChartByCaption = cht Set cht = Nothing Set chtObj = Nothing End Function Sub TestGetChartByCaption() Dim cht As Chart Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Basic Chart") Set cht = GetChartByCaption(ws, "I am the Chart Title") If Not cht Is Nothing Then MsgBox "Found chart" Else MsgBox "Sorry - chart not found" End If Set ws = Nothing Set cht = Nothing End Sub This function works by looping through all of the ChartObjects and their associated charts on the specified worksheet. For each chart, it checks to make sure the chart has a title, and if it does, the func- tion checks the title for a match. The TestGetChartByCaption procedure provides an example of how you could use the GetChartByCaption function. Basically, all you need to do is make sure that a chart was found by comparing the result to Nothing. Once you’ve found a chart to manipulate, the actual manipulation is quite easy now that you’re familiar with what I’ve covered earlier in the chapter regarding the use of colors, the Font object, the Inte- rior object, and the Border object. Listing 10.12 provides a basic example of some chart formatting. After looking over this listing, I am quite confident that you’ll recognize the chart objects and the chart elements to which they apply as shown in Figure 10.14. Also, notice how many of the chart objects, being visual in nature, use the various objects that I covered earlier in the chapter. 4281book.fm Page 231 Sunday, February 29, 2004 5:12 PM 231 CHART MANIPULATION Listing 10.12: Formatting a Basic Chart Sub FormattingCharts() Dim cht As Chart Dim ws As Worksheet Dim ax As Axis Set ws = ThisWorkbook.Worksheets("Basic Chart") Set cht = GetChartByCaption(ws, "GDP") If Not cht Is Nothing Then ' format category axis Set ax = cht.Axes(xlCategory) With ax .AxisTitle.Font.Size = 12 .AxisTitle.Font.Color = vbRed End With ' format value axis Set ax = cht.Axes(xlValue) With ax .HasMinorGridlines = True .MinorGridlines.Border.LineStyle = xlDashDot End With ' format plot area With cht.PlotArea .Border.LineStyle = xlDash .Border.Color = vbRed .Interior.Color = vbWhite .Width = cht.PlotArea.Width + 10 .Height = cht.PlotArea.Height + 10 End With ' format misc other cht.ChartArea.Interior.Color = vbWhite cht.Legend.Position = xlLegendPositionBottom End If Set ax = Nothing Set cht = Nothing Set ws = Nothing End Sub 4281book.fm Page 232 Sunday, February 29, 2004 5:12 PM 232 CHAPTER 10 EXPLORING OTHER EXCEL OBJECTS Although all of this should appear relatively straightforward, I hope that you don’t have to do much chart manipulation via code for the reasons given earlier. Creating presentation-quality charts requires an iterative design approach that can only be done manually (at least the first time). The approach is to design a nice chart manually that you then use as a template when you need to, reserving any code manipulation for relatively minor changes such as changing titles, colors, or perhaps chang- ing the source data range. Summary It’s easy to get so involved polishing your application from a programmatic standpoint that you neglect the part most noticeable to users—the look. Though it may seem trivial, the formatting of your various worksheets can go a long way toward influencing how your hard work is perceived by your end users. Therefore, it pays to make sure you give this area some attention and don’t down- play these issues. One way that you can spice up a worksheet is by applying color to its various components. You can color fonts, cell interiors, gridlines, drawing objects, and all of the visual chart-related objects and borders, among other things. Any object that has a Color property also contains a ColorIndex prop- erty. The difference is that you can specify Color using an RGB value, whereas you specify Color- Index using an index that refers to a color occupying the workbook’s color palette. Other ways that you can dress up a worksheet include using a pleasing mix of fonts (Font.Name), font sizes (Font.Size), interior patterns (Interior.Pattern), and borders. To apply these effects, use the appropriate object and property applied to a given Range object. Oh, and don’t forget about those number formats. You can set them using the NumberFormat property of the Range object. Regarding charts, although you can create them on the fly, it is best to create charts during the development process and then use them as templates, so to speak. This is because creating visually pleasing charts requires an iterative design process that requires your visual senses—a task that can’t be replaced by a computer. The conclusion of this chapter marks the end of the Excel object model section of this book. The next section covers some more advanced topics including interacting with external programs, devel- oping class modules, adding user personalization, and some Excel development best practices. I’ll kick this section off with a chapter that teaches you how to create and use your own classes. 4281book.fm Page 233 Sunday, February 29, 2004 5:12 PM Part 3 Advanced Excel Programming Techniques In this section: ◆ Chapter 11: Developing Class Modules ◆ Chapter 12: Adding User Personalization to your Application ◆ Chapter 13: Excel Development Best Practices [...]... objLoans = Nothing End Function The output of the TestCollectionObject procedure is as follows There are 5 Loan Number Loan Number Loan Number Loan Number Loan Number loans 1 has a 2 has a 3 has a 4 has a 5 has a payment payment payment payment payment of of of of of $50 6.91 $1,342 .51 $373.27 $ 852 .40 $944 .57 The procedure of interest in this listing is CollectLoanObjects Notice that the Collection object... the Raise method are described in the following list Number This is a long integer that identifies the error This should be a value between 51 3 and 65, 5 35 When using Err.Raise from within a class module, you should use the vbObjectError constant in conjunction with the desired error number IMPLEMENTING MORE ACCURATE PROPERTIES Source This is an optional string value that you can use to identify the... demonstrate Finally, you’ve defined the various properties with a data type appropriate for the kind of data that each property will hold 257 258 CHAPTER 11 DEVELOPING CLASS MODULES Summary VBA provides class modules to enable you to enjoy many, but not all, of the benefits of object-oriented programming So far throughout this book, you’ve been working with and enjoying the benefits of objects that other... something to experiment with, let’s see if you can’t demonstrate some of the advantages Using Your Object Using your own objects is a little different than using intrinsic Excel objects With all of the Excel objects you’ve used, the object already existed before you used it All you had to do was set a reference USING YOUR OBJECT to the object using the Set keyword When you did add a new Excel object such... work with multiple copies of the class where each copy is seen as a separate entity This makes programming easier because you don’t have to remember which module contains the procedure you’re looking for With an object, all of the appropriate properties and methods are available to you directly through the object variable For example, consider how hard it would be to develop Excel applications if Excel. .. End Enum 255 256 CHAPTER 11 DEVELOPING CLASS MODULES Figure 11.6 Using enumerations has the added benefit of enabling the Auto List Members feature to provide extra help When creating enumerations, keep in mind that the enumeration names must be unique compared to any other enumeration names that are in scope In order to help guarantee unique names, it is helpful to prefix the enumeration with a few... able to change the behavior of your application without get­ ting knee-deep in the code Some people refer to this type of programming as table-driven program­ ming One of the benefits of this method of programming is that you don’t have to be a programmer to change the configuration of the program and thus its behavior In order to facilitate this type of programming, I’ve created a few easy-to-use classes... would identify the “fake” object to VBA or other programmers as an object It would appear as just what it is: a collection of procedures and variables with no explicit relationship By developing a class, you’re formally declaring the collection of variables and procedures as a group of programmatic elements that are inherently related to each other and work symbiotically with one another to provide a programmatic... class modules—I’m cre­ ating wonderful applications without them What do I need class modules for?” Do you hear that voice? Don’t listen to it Although it’s true that developing and then using class modules requires you to think about programming in a different manner, that doesn’t mean it is more difficult Although you can create wonderful applications without using class modules, class modules bring... procedures I’ve tied together in regular procedures throughout this book? Is this what they mean by object-oriented programming? Throughout the book, you’ve been using objects that are intrinsic to Microsoft Excel You’ve used the Application, Workbook, Worksheet, Range, and other objects with nary a thought to the mindset regarding the underlying paradigm For the most part, didn’t it just feel natural . 4281book.fm Page 2 25 Sunday, February 29, 2004 5: 12 PM 2 25 CHART MANIPULATION With chrt ' use chart wizard to populate/format empty chart . .AxisTitle.Caption = "Year" End With With .Axes(xlValue) .HasTitle = True .AxisTitle.Caption = "GDP in billions of $" End With End With Set chrt = Nothing Set rgChartData. experiment with, let’s see if you can’t demonstrate some of the advantages. Using Your Object Using your own objects is a little different than using intrinsic Excel objects. With all of the Excel

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

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan