Browse » Home
Thursday, November 28, 2013
How to Make a Chart in the Same Sheet in VBA
1. Open Excel 2010 and show the Developer tab if it isn't already showing. Click on 'File' and then 'Options.' Click on 'Customize Ribbon' on the Categories pane. Select 'Developer' from the list of main tabs and then click on 'OK.'
2. Click on the 'Developer' tab that now should be showing in the Ribbon. Click on 'Visual Basic' to open the Visual Basic editor.
3. Double-click on the worksheet in which you want to embed the chart from the Project pain. All of the worksheets that are currently in your project is listed in the pane. The code for the worksheet will open in the Code window. If you haven't already added code to the worksheet the Code window will be blank.
4. Click on 'Insert' and then 'Procedure.' Type in a name for the procedure in the name window, leave all the other options the same and then click on 'OK.' For the example in this article, name the procedure 'embedChart.'
5. Add the code that will embed a chart into the worksheet. Click between the 'Public Sub...' and 'End Sub' declarations that are now in the Code window. You will add the code for the procedure in between the two declarations. Microsoft has developed the code that will create a chart and embed it in the current spreadsheet. Copy this code into your procedure or write your own.'Sub embedChart()Dim chtNew As ChartSet chtNew = Charts.AddSet chtNew= chtNew.Location(Where:=xlLocationAsObject, Name:='Sheet1')With chtNew.ChartType = xl3DPie'Set the data range source for the chart..SetSourceData Source:=Sheets('Sheet1').Range('A1:H2'), PlotBy:= _xlRows.HasTitle = True.ChartTitle.Text = 'My Pie Chart'End WithEnd Sub'
6. Click 'Save' on the Visual Basic editor's toolbar and close. Go to the worksheet that you embedded the chart in and check to see that it is showing.