发布的代码是一个很好的解决方案,我通过这个微小的更改使其对我有用。我通过了用户表单,因为我在模块中使用了代码。我排除了 Label、CommandButton 和 Image 以使 Valon Miller 的代码为我工作,否则所描述的运行时错误将runtime error '-2147352573 (800 200037': Member not found 显示.
Private Sub test(frm As UserForm)
Dim cCont As Control
Dim i As Integer
Dim maxIndex As Integer
Dim controls As Object
Dim key As Variant
Set controls = CreateObject("Scripting.Dictionary")
'Add controls to dictionary, key by tabindex property
For Each cCont In frm.controls
If TypeName(cCont) <> "Label" And _
TypeName(cCont) <> "Image" And _
TypeName(cCont) <> "CommandButton" Then
maxIndex = IIf(maxIndex < cCont.TabIndex, cCont.TabIndex, maxIndex)
controls.Add cCont.TabIndex, cCont
End If
Next cCont
'Get controls in order
For i = 0 To maxIndex
If controls.exists(i) Then
Debug.Print controls(i).Name & vbTab & i
MsgBox controls(i).Name
End If
Next i
End Sub
--------------------------------------------
最初我需要一个解决方案来使 sql 语句的顺序与我的表单控件的顺序同步。我想这样做:
fld1 = recordset1.value
fld2 = recordset2.value
fld3 = recordset3.value
正在寻找一种解决方案来让我的控件和我的 SQL 语句按 field1 ->recordset.value1 的顺序排列。
因此,我没有使用 taborder 对控件进行排序,而是创建了控件数组。即
sub useControlArray()
dim a as variant, rs as new recordset, strSQL as string
strSQL = "select fld1, fld2, fld3 from table"
rs.open strSQL, connection
a = array("fld1", "fld2", "fld3")
'This array would help like this:
for i = lbound(a) to ubound(a)
frm.controls(a(i)) = rs(i)
debug.print frm.controls(a(i)) ' Form is a user form
next i
end sub
这会将控件限制为使用与我的 SQL 语句中相同的顺序填充它们所需的控件数量,并且我不需要注意控件是否存在。
我希望这会有所帮助。