我正在尝试将工作表分配给变量,然后使用该工作表上的控件。我真的很困惑为什么当我可以从工作表编号中引用命名变量上的控件时。
Sub SheetNames()
Dim i As Integer
Dim pres As Worksheet
Call NumSheets
Set pres = Sheets("Presentation") 'Sheet18 (assignment works)
Sheet18.lbSheets.Clear 'This works
pres.lbSheets.Clear 'This fails (method or data member not found)
End Sub
答案 0 :(得分:2)
Worksheet
对象是一种通用的“模板”对象类型,它只具有适用于所有Worksheet
个对象的“开箱即用”属性。您的特定工作表Sheet18
添加了控件,这些控件现在是工作表对象模型的一部分,但它们不是通用Worksheet
类的一部分:您的工作表现在是更像是工作表的特定“子类”,因此您不能将其声明为Worksheet
并仍然通过该引用访问控件。
但是,您可以声明它As Sheet18
(该特定工作表的“子类”):
Sub Tester()
Dim sht As Worksheet
Dim sht2 As Sheet18
Set sht = Sheet18
Debug.Print sht.lbSheets.ListCount '<< nope - compile error because the
' Worksheet class has no
' "lbSheets" member
Set sht2 = Sheet18
Debug.Print sht2.lbSheets.ListCount '<< OK!
'but you may as well skip the variable and just use
Debug.Print Sheet18.lbSheets.ListCount
'this also works if you know the sheet name and the control name
Set sht = ThisWorkbook.Sheets("Presentation")
Debug.Print sht.OLEObjects("lbSheets").Object.ListCount
End Sub