Johan's Blog

This and that in a developer's life in general
Welcome to Blogs @ IRM Sign in | Join | Help
 Search

Disclaimer

The content of this site is my own personal opinion and does not in any way represent my employer, it's subsideries or affiliates. These postings are provided "AS IS" with no warranties, and confer no rights.

This Blog

Excel Automation - Example with Named Ranges

excel And now to something completely different... the Excel automation. Every now and then you need to open up an Excel file and do stuff with it. In this case we needed to create and read from named ranges in Excel, and it's not overy easy to get information about how to do that, so I thought I might as well post some sample code here.

To get started with Excel automation, there is a good KB-article on MSDN: http://support.microsoft.com/kb/q302094

Now, here's a console app in .NET 3.5 using VB.NET (I prefer to work with VB.NET with Office Interop and VSTO), which opens Excel, adds a new workbook, creates a (3,5) string array with values, fills the a range with these values, creates a named range and gets the values again to see that it worked properly.

Imports Microsoft.Office.Interop

Module Module1

    Sub Main()
        Dim application = New Excel.Application
        application.Visible = True
        Dim workbook = application.Workbooks.Add()
        Dim worksheet As Excel._Worksheet = workbook.ActiveSheet

        Dim saRet(3, 5) As String

        For iRow = 0 To 3
            For iCol = 0 To 5
                saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()
            Next iCol
        Next iRow
'get a range, alternative 1 'Dim range As Excel.Range = worksheet.Range("A1:E3", Reflection.Missing.Value) 'get a range, alternative 2 Dim range As Excel.Range = worksheet.Range("A1", Reflection.Missing.Value) range = range.Resize(3, 5) 'set value of range to that of the string array range.Value = saRet 'name the range, explicitly (using dollar $ sign) workbook.Names.Add("NamedRange", "=$A$1:$E$3")
'clear range range = Nothing 'get the values of the named range range = worksheet.Range("NamedRange") Dim values(,) As Object = range.Value Console.WriteLine("rows:" & values.GetUpperBound(0)) Console.WriteLine("cols:" & values.GetUpperBound(1)) Console.WriteLine("value of row 2, column 4 (D4) = " & values(2, 4)) Console.WriteLine("Press key to exit...") Console.Read() workbook.Close(False) application.Quit() End Sub End Module

Hope this helps someone.


Cross-posted from my blog at http://weblogs.asp.net/jdanforth
Published den 18 augusti 2008 16:43 by johan
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems