这是我编写的代码,它在满足条件时锁定用户表单文本框。它以重复的形式存在明显的低效率:
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