VBA Error 1004 when using Select on Excel Range.

Had a little error in my MS Access VBA when trying to use the Select method of an Excel Range. It turns out that you have to select the WorkSheet before the Range, otherwise you might get Error 1004

Sub RangeError()

    Dim xls As Excel.Application
    Dim xlsBook As Excel.Workbook
    Dim xlsSheet As Excel.Worksheet
    Dim xlsSheet2 As Excel.Worksheet

    Set xls = New Excel.Application
    Set xlsBook = xls.Workbooks.Open(PathToExcelFile)
    Set xlsSheet = xlsBook.Sheets("Sheet1")
    Set xlsSheet2 = xlsBook.Sheets("Sheet2")

    xlsSheet2.Select  'THIS LINE IS REQUIRED
    xlsSheet2.Range("C3").Select   'THIS IS THE PROBLEM LINE

End Sub

 

Add comment

Loading