我正在尝试遍历窗体上的控件以显示那些支持 ControlSource 的控件的 ControlSource 属性。
我发现识别具有 ControlSource 属性的控件相对容易。问题在于访问这些控件的属性。通用 Control 对象没有 ControlSource 属性。如果我使用另一种语言,我只需将作为列表框的控件强制转换为 ListBox 对象,例如,访问 ControlSource 属性。但我的理解是,在 VBA 中没有类型继承,所以我不能将一种类型的对象转换为另一种类型的对象。
那么如何访问那些支持该属性的控件的 ControlSource 属性呢?
到目前为止,这是我的代码:
Private Sub IterateControlsOnForm()
Dim frm As Form, formName As String
' The only controls that have a ControlSource property are either
' BoundObjectFrame controls or ListBox controls.
Dim ctrl As Control
Dim boundObjectFrame As boundObjectFrame, listBoxCtrl As listBox
Dim boundObjectFrameTypes() As String, listBoxTypes() As String
Dim ctrlType As String
formName = "MAINFORM"
' Useful way of populating a string array - use Split function.
' Array function only works with Variants.
boundObjectFrameTypes = _
Split("CheckBox,ComboBox,CustomControl,GroupLevel", ",")
listBoxTypes = Split("OptionButton,OptionGroup,TextBox,TextBox", ",")
' Assumes form is open.
Set frm = Forms(formName)
For Each ctrl In frm.Controls
' Ignore controls that do not have a ControlSource property.
ctrlType = TypeName(ctrl)
If IsStringInArray(ctrlType, boundObjectFrameTypes) Then
' **** FOLLOWING LINE FAILS ****
Set boundObjectFrame = ctrl
Debug.Print boundObjectFrame.Name & "(" & ctrlType & ") " & _
"ControlSource Property: " & boundObjectFrame.ControlSource
ElseIf IsStringInArray(ctrlType, listBoxTypes) Then
' **** FOLLOWING LINE FAILS ****
Set listBoxCtrl = frm.Controls(ctrl.Name)
Debug.Print listBoxCtrl.Name & "(" & ctrlType & ") " & _
"ControlSource Property: " & listBoxCtrl.ControlSource
End If
Next ctrl
End Sub
我尝试了两种将通用 Control 对象转换为具有 ControlSource 属性的更具体控件的方法。请参阅两条评论“ ** FOLLOWING LINE FAILS ** ”。