Programming Excel Using Visual Basic 6

Sharing is Caring

Microsoft provides the ability to programmatically created spreadsheets using Excel. The process isn’t overly complex, but the twist is that the intelisense is almost nonexistent in Visual Studio 6.0.

First we need to add a reference Microsoft Excel Object Library, on my particular Windows Computer it’s called the “Microsoft Excel 10.0 Object Library.” To be safe, we should also add the Microsoft Office Object Library; again on my particular Windows Computer it’s called “Microsoft Office 10.0 Object Library.”

We add the reference by clicking Project, and then References. Find the two object libraries mentioned and click their respective checkboxes and then click ok.

In this example, we’ll just programmatically add a couple of values to some cells, and do some basic formatting.

In the Code Window, we need to create the excel object and an excel workbook.

Dim Excl As New Excel.Application

Dim NewBook As Excel.Workbook

Dim lastRowNum as Integer ‘used to display lastRow

With Excl

Set NewBook = .Workbooks.Add

‘DisplayAlert and ScreenUpdating are two of the most useful features ‘when debugging excel, because they allow you to show excel and to hide ‘it if you don’t want the client to see if an instance of excel is running

.DisplayAlerts = False

.ScreenUpdating = False

End With

‘This next step is where we’re just going to add some data to a couple of cells

‘The format is Excel.Cells(rownumber, columnumber) . Rows and Columns ‘actually start with 1 being the first row.

With Excl

.Cells(1,1) = 5 ‘I wrote the number 5 in the first row, and first column

.Cells(1,2) = 6 ‘I wrote the number 6 in the first row, and 2nd column

.Cells(2,1) = 7 ‘I wrote the number 7 in the 2nd row, and 1st column

End With

‘Say I want to add two values using cell references

Excl.Cells(1,3). Formula = “A1+A2”

‘Let’s make the cell we just input the formula have a bold font.

‘Setting most of the front properties is as simple as selecting the cell and then ‘using .Font and finding the particular property you want to use

Excl.Cells(1,3).Font.Bold = true

‘Let’s change the Font Size to 12

Excl.Cells(1,3).Font.Size = 12

‘Saving a copy of the Excel document we have created is fairly simple

NewBook.SaveCopyAs App.Path & “test.xls”

‘Always make sure that you close the instance of Excel you opened because the ‘user will not know it is open and it can be a significant memory user.



Set NewBook = nothing

Set Excl = nothing

let me know if this was helpful!

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring