XL98: Using Visual Basic to Create a Chart Using a Dynamic Range

ID: Q193249

The information in this article applies to:

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, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals 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 needs. If you have limited programming experience, you may want to contact the Microsoft fee-based consulting line at (800) 936-5200. For more information about the support options available from Microsoft, please see the following page on the World Wide Web:

   http://www.microsoft.com/support/supportnet/refguide/

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.

Additional query words: XL98

Keywords          : kbdta kbdtacode xlvbahowto 
Version           : MACINTOSH:98
Platform          : MACINTOSH
Issue type        : kbhowto

Last Reviewed: May 18, 1999