Skip to Main Content
Excel 2003 Programming: A Developer's Notebook
book

Excel 2003 Programming: A Developer's Notebook

by Jeff Webb
August 2004
Intermediate to advanced content levelIntermediate to advanced
312 pages
8h 30m
English
O'Reilly Media, Inc.
Content preview from Excel 2003 Programming: A Developer's Notebook

Work with Excel Objects in .NET

Once you’ve got an instance of the Excel Application object, you can use it to get at any of the other objects in the Excel object library.

How to do it

VB.NET has an Imports declaration that you can use to create a shortcut for referring to objects from a particular library. For example, the following class-level declaration:

   Imports Microsoft.Office.Interop

shortens the Excel application declaration to:

   Dim WithEvents m_xl As Excel.Application

which is easier to type and read. Notice that you don’t use Set to get object references in VB.NET. For example, the following code gets a reference to Workbook and Range objects to display powers of 2 on a worksheet:

   ' .NET code.
   Dim wb As Excel.Workbook, rng As Excel.Range
   ' Create a new workbook.
   wb = m_xl.Workbooks.Add(  )
   ' Add some data
   For i As Integer = 1 To 10
       rng = wb.Worksheets(1).Cells(1, i)
       rng.Value = 2 ^ i
   Next

VB.NET could get rid of Set because it also got rid of default members. In VBA, you can assign a value to a Range object because the Value property is the default member of the Range object. This is a clearer approach to a language—default members were never a very good idea.

This change can take some getting used to, especially if you don’t explicitly declare a type for a variable. For example, the following .NET code gets a reference to a Range object, but then replaces that reference with an integer:

 Dim obj ' Gets a reference to the A1 range object. obj = wb.Worksheets(1).Cells(1, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Microsoft® Office Excel 2003 Programming Inside Out

Microsoft® Office Excel 2003 Programming Inside Out

Curtis Frye, Wayne S. Freeze, Felicia K. Buckingham
Excel® 2007 VBA Programmer's Reference

Excel® 2007 VBA Programmer's Reference

John Green, Stephen Bullen, Rob Bovey, Michael Alexander
Office 2003 XML

Office 2003 XML

Simon St. Laurent, Mary McRae, Evan Lenz

Publisher Resources

ISBN: 0596007671Supplemental ContentCatalog PageErrata