以下是我编写的代码,用于在满足条件时锁定userform文本框。它以重复的形式存在明显的低效率:
With txtESPPStock
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtChildLife
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtHealthcareFSA
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtLtdPlusBuyUp
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtMedicalDental
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtSpouseLife
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtStdPlusBuyUp
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtSupplementalLife
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txtVision
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
With txt401kReg
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
由于所有内部设置都相同,看起来如果我只是足够聪明,我可以用更少的行编码。我想要的是,对于每个文本框,可以说:
With txtESPPStock
Call GetProperties
End With
或者甚至更好,将所有需要属性设置的属性放在一个数组中,这样我就可以执行以下操作:
For txtFieldNumber = 0 To 15
For PropertySettings = 0 To 3
ArrayValue(txtFieldNumber, PropertySettings) = getproperty(PropertySettings)
Next PropertySettings
Next txtFieldNumber
也许我接近最后一个的结构,但我似乎缺乏一些知识,这使我明白如何做到这一点。任何人都可以帮我理顺吗?
在学习之后,你可以循环遍历数组,就像循环遍历范围一样,我能够按照我的预期减少代码,并制作一个可以被其他用户表单重用的工具,而无需再次编码设置:
Sub SetLockedFields(ByRef arrLockedFields() As Variant)
Dim varFieldToLock As Variant
For Each varFieldToLock In arrLockedFields
With frmPaycheckEntry.Controls(varFieldToLock)
.Locked = True
.BackColor = &H80000000
.value = ""
.Enabled = False
End With
Next
End Sub
要完成上面第一个代码示例中显示的所有工作,我现在只需将文本字段放在变量数组中并传递它们,如下所示:
Private Sub UserForm_Initialize()
Dim arrLockedFields() As Variant
.
.
.
If <condition is met> Then
ReDim arrLockedFields(1 To 11)
arrLockedFields = Array("txtBasicLife", "txtChildLife", _
"txtESPPStock", "txtHealthcareFSA", _
"txtLtdPlusBuyUp", "txt401kReg", _
"txtMedicalDental", "txtSpouseLife", _
"txtStdPlusBuyUp", "txtSupplementalLife", _
"txtVision")
End If
Call SetLockedFields(arrLockedFields)
End Sub
答案 0 :(得分:1)
是的,您可以使用循环来避免重复代码。
Sub t1()
Dim ctrl As Control
For Each ctrl In UserForm1.Controls
'Check if the control is a textbox
If TypeName(ctrl) = "TextBox" Then
With UserForm1.Controls(ctrl.Name)
.Locked = True
.BackColor = &H80000000
.Value = ""
.Enabled = False
End With
End If
Next
End Sub
另一个例子:当你有某些名字时
Private Sub CommandButton1_Click()
Dim names() As Variant
Dim name As Variant
names = Array("TextBox1", "TextBox2")
For Each name In names
With UserForm1.Controls(name)
.Locked = True
.BackColor = &H80000000
.Value = ""
.Enabled = False
End With
Next
End Sub