Article ID: 114378
Article Last Modified on 6/29/2004
112417 How To Create Excel Chart w/ OLE Automation from Visual Basic
Dim oWDBasic As Object
' By making this object global to the Form, Word will not close down
' once the Command1_Click event is finished. If this variable where
' declared within the Click event, the scope of the variable would be
' local to the Click event. In which case, when the Click event ended,
' the variable would be de-allocated, and Word would unload without
' making needed changes to the document and without saving changes made
' by the code in the Click Event.
Sub Command1_Click ()
' Create XLChart and copy it.
CreateXLChart
Set oWDBasic = CreateObject("Word.Basic")
' Create a new document based on template previously created
oWDBasic.FileNew "C:\WINWORD\TEMPLATE\MYREPORT.DOT"
' Insert chart into document where the bookmark 'Chart1' exists
oWDBasic.EditGoto "Chart1"
oWDBasic.EditPaste
' Save new document to disk
oWDBasic.FileSaveAs "C:\WINWORD\REPORT.DOC"
End Sub
Sub CreateXLChart ()
Dim objXLsheet As Object ' reference to Excel Worksheet
Dim objRange1 As Object ' reference to the first series in chart
Dim objRange2 As Object ' reference to the second series in chart
Dim objChart1 As Object ' reference to the chart created
Dim iRow As Integer ' Index variable for the current Row
Dim iCol As Integer ' Index variable for the current Row
Dim strTmpRange As String ' Temporarily hold Range in R1C1 notation
Const cNumCols = 10 ' Number of points in each Series
Const cNumRows = 2 ' Number of Series
' Create a Worksheet Object
Set objXLsheet = CreateObject("Excel.Sheet")
Randomize Timer
' Insert Random data into Cells for the two Series:
For iRow = 1 To cNumRows
For iCol = 1 To cNumCols
objXLsheet.Cells(iRow, iCol).Value = Int(Rnd * 50) + 1
Next iCol
Next iRow
' Insert Named Ranges:
For iRow = 1 To cNumRows
' Enter the following two lines as one, single line of code:
strTmpRange = "R" & iRow & "C" & Format$(1) & ":R" & iRow & "C"
& Format$(cNumCols)
' Enter the following two lines as one, single line of code:
objXLsheet.Parent.Names.Add "Range" & Format$(iRow), "=Sheet1!" &
strTmpRange
Next iRow
' Add a ChartObject to the worksheet:
Set objChart1 = objXLsheet.ChartObjects.Add(100, 100, 200, 200)
' Assign the Ranges created above as the individual series
' for the chart:
For iRow = 1 To cNumRows
objChart1.Chart.SeriesCollection.Add "Range" & Format$(iRow)
Next iRow
' Copy Chart for paste into the Word Report:
objChart1.Copy
' Close this instance of Excel without saving changes:
objXLsheet.Parent.Saved = True
objXLsheet.application.Quit
End Sub
Keywords: kbhowto kbprogramming KB114378