【发布时间】:2014-10-15 17:41:08
【问题描述】:
Worksheet 和 Workbook 对象可以通过两种方式访问其属性。
- 明确 ➔
Sheet1.cells(1,2) - 隐式 ➔
Cells(1,2)
我很好奇的是,当隐式调用属性时,VBA 如何知道要使用哪个对象?是否还有更多对象与这些隐式调用兼容?
这是我进行的一个简单实验,它显示了对象焦点发生变化和不发生变化的一些情况:
'Sheet1 has 2 row in column A
'Sheet2 has 5 rows in column A
Sub test()
Dim obj As Object
Set obj = Sheet1
'focus is set when a sheet is called directly
row1 = Sheet2.Range("A" & Rows.Count).End(xlUp).Row
'focus is set when a sheet is called through reference
row2 = obj.Range("A" & Rows.Count).End(xlUp).Row
'focus is not set by with
With Sheet2
row3 = Range("A" & Rows.Count).End(xlUp).Row
End With
'output = 5 : 2 : 2
MsgBox row1 & " : " & row2 & " : " & row3
End Sub
【问题讨论】:
-
您的
With使用不正确 - 应该是.Range("A" & .Rows.Count).End(xlUp).Row- 请注意前导句点 -
谢谢,但这实际上是故意的。我试图查看是否可以通过 with 语句本身将焦点切换到 sheet2。
-
那么这就解释了为什么它什么也没做;-)