我想使用变量来引用控件对象



这看起来很简单,但我无法掌握它。提前感谢您的帮助。

我想调用一个函数,将文本框的名称和值传递给变量,然后使用该变量或其他变量来引用该文本框的值。我不知道如何使用变量来引用对象的名称并将其用作该对象。

我正在尝试自动化一个在用户表单中使用许多文本框值的例程,这样我就不会用 400 次重复代码 800 不同的变量。

我尝试了我能想到的所有措辞来搜索其他类似的问题,它们要么太复杂而无法理解,要么我甚至不确定它是否适用于我想要的东西。

'IsolationQty & IsolationCheckBox are what I want to replace with variables
'Determine emptyRow & Fill sheet
If IsolationCheckBox.Value = True Then
For i = 1 To IsolationQty
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
'Transfer information
Cells(emptyRow, 1).Value = SysID.Value
Cells(emptyRow, 2).Value = InspectID.Value
Cells(emptyRow, 3).Value = LocID.Value
Cells(emptyRow, 4).Value = LayoutID.Value
Cells(emptyRow, 5).Value = "=VLOOKUP(" & Chr(34) & IsolationCheckBox.ControlTipText & Chr(34) & ", Device_Types, 2, FALSE)"
Cells(emptyRow, 6).Value = IsolationCheckBox.ControlTipText
Next i
End If

我总是以与带有变量的略有不同的方式实现这一点。我想提出不同类型的解决方案。

这很简单。首先循环访问用户窗体的控件集合。读取每个控件名称并解决其属性,如下面的代码所示。

我希望它有所帮助。

Sub LoopThroughControls()
Dim Controls As Controls
Dim control As control
Dim ControlName As String
Set Controls = UserForm1.Controls
For Each control In Controls
'Make Sure not to get or set property of a control which does not exist
'First use VBA.TypeName to check control type and address object properties accordingly
If VBA.TypeName(control) = "Label" Then Debug.Print (UserForm1.Controls.Item(control.Name).Caption)
If VBA.TypeName(control) = "TextBox" Then Debug.Print (UserForm1.Controls.Item(control.Name).Value)
Debug.Print (UserForm1.Controls.Item(control.Name).Name)
Next control
End Sub

最新更新