Skip to content


HOWTO: Find the first and last used row and column in an Excel spreadsheet

If you want to know how many rows and / or columns there are in an excel sheet, you can use the UsedRange object.
This is a much better solution than looping over all rows and columns looking for the boundaries.

Private Sub cmdLoad_Click()
Dim excel_app As Object
Dim excel_sheet As Object
Dim new_value As String
Dim first_row As Integer
Dim first_col As Integer
Dim num_rows As Integer
Dim num_cols As Integer
 
    ' Create the Excel application.
    Set excel_app = CreateObject("Excel.Application")
 
    ' Uncomment this line to make Excel visible.
'    excel_app.Visible = True
 
    ' Open the Excel spreadsheet.
    excel_app.Workbooks.Open FileName:=txtExcelFile.Text
 
    ' Check for later versions.
    If Val(excel_app.Application.Version) >= 8 Then
        Set excel_sheet = excel_app.ActiveSheet
    Else
        Set excel_sheet = excel_app
    End If
 
    ' Get and display the bounds.
    first_row = excel_sheet.UsedRange.Row
    first_col = excel_sheet.UsedRange.Column
    num_rows = excel_sheet.UsedRange.Rows.Count
    num_cols = excel_sheet.UsedRange.Columns.Count
 
    MsgBox "Rows: " & Format$(first_row) & _
        " - " & Format$(first_row + num_rows - 1) & vbCrLf _
            & _
        "Cols: " & Format$(first_col) & _
        " - " & Format$(first_col + num_cols - 1)
 
    ' Comment the rest of the lines to keep
    ' Excel running so you can see it.
 
    ' Close the workbook without saving.
    excel_app.ActiveWorkbook.Close False
 
    ' Close Excel.
    excel_app.Quit
    Set excel_sheet = Nothing
    Set excel_app = Nothing
End Sub

Posted in Performance, VBA. Tagged with , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.