XL98: Using Visual Basic to Create a Chart Using a Dynamic Range (193249)



The information in this article applies to:

  • Microsoft Excel 98 Macintosh Edition

This article was previously published under Q193249

SUMMARY

When you record a macro to create a chart, the source address of cells used to create the chart is fixed by Microsoft Excel. This article contains a sample Microsoft Visual Basic for Applications macro that you can use to create a chart when the source address containing the data to be used in the chart may vary.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. Follow these steps to create the sample macro:

  1. Enter the following information in a new worksheet:
          C3:         D3:  Region 1   E3:  Region 2   F3:  Region 3
          C4:  Jan    D4:  10         E4:  80         F4:  15
          C5:  Feb    D5:  20         E5:  70         F5:  25
          C6:  Mar    D6:  30         E6:  60         F6:  35
          C7:  Apr    D7:  40         E7:  50         F7:  45
    						
  2. Start the Visual Basic Editor (press OPTION+F11).
  3. On the Insert menu, click Module.
  4. Type the following code in the module sheet:
          Sub CreateChart()
    
             Dim ChartRange As Range
    
             ' Set variable to the entire region to be charted.
             Set ChartRange = Range("c4").CurrentRegion
    
             ' Add a new chart to the worksheet.
             Charts.Add
    
             With ActiveChart
    
                ' Set the type of chart.
                .ChartType = xlLineMarkers
    
                ' Set the source range for the chart.
                .SourceData Source:=ChartRange
    
                ' This macro assumes that your data resides n a worksheet named
                ' "Sheet1". Change the Name argument to match the name of your
                ' worksheet.
                .Location Where:=XlLocationAsObject, Name:="Sheet1"
             End With
           End Sub
    						
  5. Activate the worksheet where you entered the data in step 1 and run the CreateChart macro.
A new chart is created on your worksheet.

Modification Type:MajorLast Reviewed:6/17/2005
Keywords:kbdtacode kbhowto KB193249