Creating Excel Spreadsheets and Charts from VB | CodeGuru

Creating Excel Spreadsheets and Charts from VB

This article will show you how to create a new work book, create sheets within that work book, populate the sheets, and create a graph (chart) using data keyed into the sheet. I have a helpdesk-type application where we report on the number of new calls (Issues), calls fixed, and calls that convert into bug […]

Written By
CodeGuru Staff
CodeGuru Staff
Aug 10, 2004
2 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

This article will show you how to create a new work book, create sheets within that work book, populate the sheets, and create a graph (chart) using data keyed into the sheet.

I have a helpdesk-type application where we report on the number of new calls (Issues), calls fixed, and calls that convert into bug fixes (Stirs).

The helpdesk is broken up into a number of systems; for example, AS/400, NT, and so forth. An issue can be created for any system, so the program will create a sheet for each system.

The first thing to do is to create a reference to the Excel object. In my case, that’s the Excel 9.0 object library. My program defines the following:

Dim objExcelA  As Excel.Application
Dim objExcelW  As Excel.Workbook
Dim objExcelSI As Excel.Worksheet    ‘Issues Work Sheet
Dim objExcelSS As Excel.Worksheet    ‘Stirs Work Sheet
Dim objExcelCI As Excel.Chart
Dim cho        As Excel.ChartObject
Dim ch         As Excel.Chart
‘Dim objExcelCI As Excel.Charts
Dim objExcelCS  As Excel.ChartObject
Dim adrQry As ADODB.Recordset
Dim adrChgType As ADODB.Recordset
Dim Row As Long
Dim chgtype As Long
Dim LastCell As String
Dim statYear As String
Dim bkmark As Variant

StatYear is used by the user. They can select statistics for a particular year or over the full term of the helpdesk (in other words, to give a trend of calls). The following code determines where the user is going to store the new Excel sheet:

With dlgFileLocation
   .DefaultExt  = “.XLS.DialogTitle = “Where is the Spread Sheet”
   .filter      = “Excel SpreadSheet|*.XLS|All Files|*.*”
   .FilterIndex = 1
   .FileName    = “Issue Statistics”
   .CancelError = True
   .Flags = FileOpenConstants.cdlOFNHideReadOnly + _
            FileOpenConstants.cdlOFNCreatePrompt + _
            FileOpenConstants.cdlOFNOverwritePrompt
   .InitDir = “C:TEMP.ShowSave
End With

Get the statistics year from the user:

statYear = InputBox(“Do you want the stats for any particular year? _
           (0 implies all years)”, “Stats for a year”, 0)
If statYear = “” ThenUser probably pressed CANCEL
   Exit Sub
End If

Load Excel and start to build the record set that will hold the data for the spreadsheet:

Set objExcelA = New Excel.Application
Set objExcelW = objExcelA.Workbooks.add
Set adrQry    = New ADODB.Recordset

Create/Open the recordset:

With adrQry
   If statYear = “0Then
      .Source  = “Statistics Order By ChangeType, StatsDate”
   Else
      .Source = “Statistics where Left$(statsdate, 4) = ” & _
         Chr$(39) & statYear & Chr$(39) & _
         ” Order By ChangeType, StatsDate”
   End If
       .CursorLocation   = adUseClient
       .CursorType       = adOpenDynamic
       .LockType         = adLockReadOnly
       .ActiveConnection = adoConnection
       .Open , , , , adCmdTable
End With

Get the list of systems defined in the helpdesk:

Set adrChgType       = New ADODB.Recordset
With adrChgType
   .Source           =Systems”
   .CursorLocation   = adUseClient
   .CursorType       = adOpenDynamic
   .LockType         = adLockReadOnly
   .ActiveConnection = adoConnection
   .Open , , , , adCmdTableDirect
   bkmark            = .bookmark
End With

(Change Type and system are defined as the same thing.)

We will now load the spreadsheet. If we have encountered a new system, the first column of the spreadsheet should have column headings:

Do While Not adrQry.EOF
   If chgtype <> adrQry.Fields(ChangeType) Then
      adrChgType.FindSystemId =& adrQry.Fields(ChangeType), _
                                  , adSearchForward, bkmark
      Set objExcelSI  = objExcelW.Worksheets.add
      objExcelSI.Name = adrChgType.Fields(ChangeType) & ” – Issueschgtype         = adrQry.Fields(ChangeType)
      Set objExcelSS  = objExcelW.Worksheets.add
      objExcelSS.Name = adrChgType.Fields(System) & ” – StirsobjExcelSI.Cells(1, 1).Value =Year / WeekobjExcelSI.Cells(1, 2).Value =Curent OutstandingobjExcelSI.Cells(1, 3)       =New Issues This WeekobjExcelSI.Cells(1, 4)       =Completed Issues This WeekobjExcelSS.Cells(1, 1).Value =Year / WeekobjExcelSS.Cells(1, 2).Value =Outstanding StirsobjExcelSS.Cells(1, 3).Value =New Stirs This WeekobjExcelSS.Cells(1, 4)       =Completed Stirs This WeekRow = 2
      objExcelW.Charts.add
      Set objExcelCI = objExcelW.ActiveChart
      objExcelCI.Activate
      objExcelCI.Name = adrChgType.Fields(System) & ” – Issues ChartEnd If

We have now created a two new sheets: one for the issues (SI) and one for the Stirs/bug fixes (SS). We have also created a chart sheet (the chart sheet will only show a graph of the issues). We will now load the data into the sheet:

objExcelSI.Cells(Row, 1).Value = adrQry.Fields(“StatsDate”)
objExcelSI.Cells(Row, 2).Value = adrQry.Fields(“Curent Outstanding”)
objExcelSI.Cells(Row, 3) = adrQry.Fields(“New Issues This Week”)
objExcelSI.Cells(Row, 4) = adrQry.Fields(“Completed Issues This Week”)
objExcelSS.Cells(Row, 1).Value = adrQry.Fields(“StatsDate”)
objExcelSS.Cells(Row, 2).Value = adrQry.Fields(“Outstanding Stirs _
                                                This Week”)
   adrQry.MoveNext

If we have encounted the end of the recordset or the system/change type has changed, we need to build the chart/graph:

If adrQry.EOF Then
      LastCell =D& Mid$(Str$(Row), 2)
      objExcelCI.SetSourceData objExcelSI.Range(a1:& _
                                                LastCell), _
                                                xlColumns
      objExcelCI.ChartType       = xlLineMarkers
      objExcelCI.Legend.Position = xlLegendPositionBottom
      objExcelCI.HasTitle        = True
      objExcelCI.ChartTitle.Text = objExcelCI.Name
Else
      If chgtype <> adrQry.Fields(ChangeType) Then
         LastCell =D& Mid$(Str$(Row), 2)
         objExcelCI.SetSourceData objExcelSI.Range(a1:& _
                                                   LastCell), _
                                                   xlColumns
         objExcelCI.ChartType       = xlLineMarkers
         objExcelCI.Legend.Position = xlLegendPositionBottom
         objExcelCI.HasTitle        = True
         objExcelCI.ChartTitle.Text = objExcelCI.Name
      End If
   End If
   Row = Row + 1
Loop

The variable Row is incremented as we write a new row, so the line LastCell = “D” & Mid$(Str$(Row), 2) sets LASTCELL to something like D10.

objExcelCI.SetSourceData objExcelSI.Range(“a1:” & LastCell), _
                                          xlColumns

This line tells the chart the range of the data it is to use.

objExcelCI.ChartType = xlLineMarkers

I want my graph to be a line graph.

objExcelCI.Legend.Position = xlLegendPositionBottom

The legend is to go at the bottom of the screen:

objExcelCI.HasTitle        = True
objExcelCI.ChartTitle.Text = objExcelCI.Name

The chart has a title and the title should be the same as the issues spreadsheet that created it.

Time to close everything now:

objExcelA.DisplayAlerts = False
objExcelW.SaveAs dlgFileLocation.FileName
objExcelA.Quit
Set objExcelA  = Nothing
Set objExcelW  = Nothing
Set objExcelSI = Nothing
Set objExcelSS = Nothing
Set objExcelCI = Nothing
Set objExcelCS = Nothing
If adrQry.State     = adStateOpen Then
   adrQry.Close
End If
If adrChgType.State = adStateOpen Then
   adrChgType.Close
End If
Set adrQry      = Nothing
Set adrChgType  = Nothing
Me.MousePointer = vbNormal
Exit Sub
CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.