Login   /   Register

Read Excel range into an array

Rate this article
     1 votes, average: 3 out of 51 votes, average: 3 out of 51 votes, average: 3 out of 51 votes, average: 3 out of 51 votes, average: 3 out of 5
Loading ... Loading ...
May 1st, 2008 by Yaron Assa

Usually, we only want to read some data from an Excel worksheet, and we’ll be more than happy to get that data in a simple 2-dimensional array.

Later we can loop through the array, and access the data in a quick and easy fashion.

Here’s a function which receives an Excel file, the workbook name and returns its contents as a two dimensional array.

   1: Function ReadExcel(sFileName,sSheetName)
   2:    Dim oExcel
   3:    Dim oRange
   4:    Dim arrRange
   5:  
   6:    'Open the file and set the sheet
   7:    On Error Resume Next
   8:       Set oExcel = CreateObject("Excel.Application")
   9:       oExcel.Workbooks.Open(1)
  10:       Set oRange = oExcel.Worksheets(sSheetName).UsedRange
  11:  
  12:       If Err.Number <> 0 Then
  13:          ReadExcel = Array("Error")
  14:          Exit Function
  15:       End If
  16:    On Error Goto 0
  17:   
  18:    'Cast excel data into a two-dimentional array
  19:    arrRange = oRange.Value
  20:    
  21:    oExcel.WorkBooks.Item(sFileName).Close
  22:    Set oRange = Nothing
  23:    oExcel.Quit
  24:    Set oExcel = Nothing
  25:  
  26:    'return the arrRange and then return to the function
  27:    ReadExcel = arrRange
  28:              
  29: End Function

Posted in MS-Excel

4 Responses to “Read Excel range into an array”

  1. ferdman Says:

    [+]

    I've applied this function to my library and it works rather well. However, I keep getting a subscript out of range error on line ... ...

  2. ferdman Says:

    [+]

    Should line 21 in the original post be this instead? oExcel.WorkBooks.Close insetad of oExcel.WorkBooks.Item(sFileName).... ...

  3. Yaron Assa Says:

    [-]

    Thanks ferdman,
    I’ve fixed the function.

  4. benschubert Says:

    [+]

    I'm not sure if this is the same thing but you don't need to define an array when getting certain data out of Excel. I did this c... ...

Leave a Reply

You must be logged in to post a comment.

This article was viewed 1178 times