我不知道在不活动的工作簿上引用工作表的正确方法是什么。
我有以下代码:
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
现在我想参考trackBook上的工作表。我试图设置一个变量:
Set trackSheet = trackBook.Worksheets("sheet1")
我得到运行时错误9:下标超出范围。
我还尝试了不设置工作表变量的情况:
firstEmpty = trackBook.Worksheet("sheet1").Range("A" & Rows.Count).End(xlUp).Row + 1
,我收到运行时错误438:对象不支持此属性或方法。
在两种情况下我都做错了什么,我应该怎么做?
答案 0 :(得分:0)
此语法正确:
Set trackSheet = trackBook.Worksheets("sheet1")
并且下标超出范围错误表明所涉及的工作簿不包含名为“ sheet1”的工作表。
此语法不正确:
firstEmpty = trackBook.Worksheet("sheet1").Range...
,并且错误消息指示“ trackBook”对象不包含属性或方法Worksheet
(应为复数:Worksheets
)。
我将在调试器下运行,在行Set trackSheet = trackBook.Worksheets("sheet1")
上中断,然后在“监视”窗口中检查Worksheets属性。特别要检查每个工作表的名称。
答案 1 :(得分:0)
使用Workbooks.Open method (Excel)
示例
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
答案 2 :(得分:0)
尝试下面的代码,虽然更长一些,但是在Workbook
和Worksheet
场景中有错误处理。
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