向用户窗体添加控件时,以下内容有什么区别。我对何时适合使用其中任何一种感到困惑。
Dim aButton1 as MSFORMS.CommandButton
Dim aButton2 as Control.CommandButton
Dim aButton3 as CommandButton
首先添加用户窗体。然后在VBA IDE 中按 F2,出现对象浏览器。在左上角是组合框,选择MSForms。在类列表中,您可以看到属于 MSForms 对象库的类。
您可以在该列表中看到CommandButton和Control :
要在代码中声明类型为 CommandButton 的变量:
Dim button1 As MSForms.CommandButton
Dim button2 As CommandButton
变量 button1 肯定是 MSForms 中的 CommandButton 类型。button2 可以是您自己在本地 VBA 项目中定义的类......但如果您的本地 VBA 项目不包含任何具有此类名称的类,则它也将被 MSForms 考虑。但是,如果您引用另一个对象库说“MSFoo”,它也将包含类 CommandButton,您将必须像这样声明它们完全合格:
Dim button1 As MSForms.CommandButton
Dim button2 As MSFoo.CommandButton
要在代码中声明 Control 类型的变量:
Dim controlObject As MSForms.Control
使用 Control 类型的变量,例如控件的基类。例如枚举 Controls 集合:
For Each controlObject In Me.Controls
Debug.Print VBA.TypeName(controlObject)
Next controlObject
或者作为函数中的参数,它不仅需要一种类型的控制:
Private Sub PrinControlName(ByRef c As MSForms.Control)
Debug.Print c.Name
End Sub
所以我认为使用像 MSForms.CommandButton 这样的完全限定名称通常是合适的。使用 Control.CommandButton 是错误的,并且在您引用某个名为“Control”且其中包含类 CommandButton 的对象库之前不会编译。
编辑:
这是一个本地创建的类的示例,其名称与 MSForm.CommandButton 相同:
以及TypeName和TypeOf在这种情况下如何工作:
Option Explicit
Private m_buttonMsForms As MSForms.CommandButton
Private m_buttonLocal As CommandButton
Private Sub UserForm_Initialize()
Set m_buttonMsForms = Me.Controls.Add( _
"Forms.CommandButton.1", "testMsButton", True)
Set m_buttonLocal = New CommandButton
m_buttonLocal.Name = "testLocalButton"
Debug.Print "We have two instances of two different button types: " & _
m_buttonLocal.Name & " and " & m_buttonMsForms.Name
' Check instances with TypeName function
' TypeName function returns same results
If VBA.TypeName(m_buttonMsForms) = VBA.TypeName(m_buttonLocal) Then
Debug.Print "TypeName of both buton types returns same result"
End If
' Check instances with TypeOf operator
' TypeOf doen't work with not initialised objects
If m_buttonLocal Is Nothing Or m_buttonMsForms Is Nothing Then _
Exit Sub
' TypeOf operator can distinguish between
' localy declared CommandButton type and MSForms CommandButton
If TypeOf m_buttonLocal Is MSForms.CommandButton Then _
Debug.Print "m_buttonLocal Is MSForms.CommandButton"
If TypeOf m_buttonMsForms Is CommandButton Then _
Debug.Print "m_buttonMsForms Is CommandButton"
If TypeOf m_buttonLocal Is CommandButton Then _
Debug.Print "m_buttonLocal Is CommandButton"
If TypeOf m_buttonMsForms Is MSForms.CommandButton Then _
Debug.Print "m_buttonMsForms Is MSForms.CommandButton"
End Sub
输出:
We have two instances of two different button types: testLocalButton and testMsButton TypeName of both buton types returns same result m_buttonLocal Is CommandButton m_buttonMsForms Is MSForms.CommandButton
数字 1 和 3 创建相同类型的控件。第一条语句是完全限定的 - 相当于使用 Dim ws 作为 WorkSheet 或 Dim ws 作为 Excel.WorkSheet。
我不熟悉第二种类型 - “Control.CommandButton” - 它不会在 Excel 2010 的用户表单中为我编译。