简体   繁体   中英

Refer to a sheet on a non-active workbook

I can't figure it out what is the right way to reference a sheet on a workbook that is not active.

I have the following code:

Dim lastRow As Integer
Dim firstEmpty As Integer
Dim trackBook As Workbook
Dim trackSheet As Worksheet       

Set trackBook = Application.Workbooks.Item("Tracking Sheet.xlsx")
lastRow = Range("A" & Rows.Count).End(xlUp).Row

And now I want to refer to a sheet on trackBook. I tried to set a variable:

Set trackSheet = trackBook.Worksheets("sheet1")

And I get run-time error 9: subscript out of range.

I also tried to do it without setting a worksheet variable:

firstEmpty = trackBook.Worksheet("sheet1").Range("A" & Rows.Count).End(xlUp).Row + 1

and I get run-time error 438: Object doesn't support this property or method.

What am I doing wrong in both cases and I should this be done?

This syntax is correct:

Set trackSheet = trackBook.Worksheets("sheet1")

and the subscript out of range error suggests the workbook in question doesn't contain a worksheet named "sheet1".

This syntax is incorrect:

firstEmpty = trackBook.Worksheet("sheet1").Range...

and the error message indicates that the "trackBook" object doesn't contain a property or method Worksheet (should be plural: Worksheets ).

I would run under the debugger, break on the line Set trackSheet = trackBook.Worksheets("sheet1") , and examine the Worksheets property in the Watch window. In particular, examine the names of each worksheet.

Work with Workbooks.Open method (Excel)

Example

Option Explicit
Public Sub Example()
    Dim xlBook As Excel.Workbook
    Set xlBook = Workbooks.Open("C:\Temp\Book1.xlsm")

    Debug.Print xlBook.Sheets("Sheet1").Range("A1").Value

        xlBook.Close SaveChanges:=False
End Sub

Try the code below, it's a little longer, but it has error handling for Workbook and Worksheet scenarios.

Dim trackBook As Workbook
Dim trackSheet As Worksheet
Dim lastRow As Long, firstEmpty As Long


' set the workbook object (if workbook is already open)
On Error Resume Next
Set trackBook = Workbooks("Tracking Sheet.xlsx")
On Error GoTo 0
If trackBook Is Nothing Then ' workbook is not open >> open it
    trackBook = Workbooks.Open(Filename:="C:\YourEntirePath\Tracking Sheet.xlsx")
End If

' set the worksheet object
On Error Resume Next
Set trackSheet = trackBook.Worksheets("sheet1")
On Error GoTo 0
If trackSheet Is Nothing Then
    MsgBox "Worksheet 'sheet1' doesn't exists in workbook, check sheet's name", vbCritical, "Worksheet Name Error"
    Exit Sub
End If

With trackSheet
    firstEmpty = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 ' get first empty row in column A
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM