我是VBA和Microsoft Access的新手。我已经阅读了几个关于这个主题的帖子,但无法弄清楚我做错了什么。或者,如果我可能错过了参考?我想将几个组合框添加到一个数组中,然后重用该数组来做各种事情,比如让它们可见或不可用等等。
我一直在尝试的代码是这样的 - 我尝试使用Control,AccessObject,ComboBox作为数组类型并获取:对象变量或者没有设置块变量 - 任何想法我做错了什么?
Private Sub Form_Load()
Dim arrayComboBox(3) As Control
Set arrayComboBox(0) = Me.cmbTourStops1
Set arrayComboBox(1) = Me.cmbTourStops2
arrayComboBox(0).Visible = False
arrayComboBox(1).Visible = True
End Sub
谢谢!
答案 0 :(得分:0)
组合框的数组应该在表单级别声明,即在模块的顶部和任何子例程或函数之外。这样,表单代码中的所有例程都可以看到它。此外,您可以使您的例程更通用(减少对特定控件名称的依赖)。见下文:
Option Compare Database
Option Explicit
Private arrayComboBox() As ComboBox
Private Sub Form_Load()
Dim howMany, i As Integer
Dim ctl As Control
Dim cbo As ComboBox
'--- count how many ComboBoxes we have on this form
howMany = 0
For Each ctl In Me.Form.Controls
If ctl.ControlType = acComboBox Then
howMany = howMany + 1
End If
Next ctl
'--- now properly size the array and store the
' controls
If howMany > 0 Then
Debug.Print "we found " & howMany & " ComboBoxes on the form"
ReDim arrayComboBox(1 To howMany) As ComboBox
i = 1
For Each ctl In Me.Form.Controls
If ctl.ControlType = acComboBox Then
Set arrayComboBox(i) = ctl
Debug.Print "added " & ctl.Name
End If
Next ctl
End If
End Sub