如何在VBA中循环

时间:2017-06-21 17:32:46

标签: vba loops iif-function

如何在vba代码中重复if函数Hello,我在表单上使用if创建命令行。但我无法一遍又一遍地写它。有没有正确的方法来简化这种写作?

If UserForm1.checkbox15.Value = True Then
UserForm2.textbox1.enable = True
UserForm2.textbox1.BackColor = RGB(200, 200, 200)
Else
UserForm2.textbox1.enable = True
UserForm2.textbox1.BackColor = RGB(255, 255, 255)
End If

If UserForm1.checkbox16.Value = True Then
UserForm2.textbox2.enable = True
UserForm2.textbox2.BackColor = RGB(200, 200, 200)
Else
UserForm2.textbox2.enable = True
UserForm2.textbox2.BackColor = RGB(255, 255, 255)
End If

If UserForm1.checkbox17.Value = True Then
UserForm2.textbox3.enable = True
UserForm2.textbox3.BackColor = RGB(200, 200, 200)
Else
UserForm2.textbox3.enable = True
UserForm2.textbox3.BackColor = RGB(255, 255, 255)
End If

If UserForm1.checkbox18.Value = True Then
UserForm2.textbox4.enable = True
UserForm2.textbox4.BackColor = RGB(200, 200, 200)
Else
UserForm2.textbox4.enable = True
UserForm2.textbox4.BackColor = RGB(255, 255, 255)
End If

...... ....到textbox660 ......

1 个答案:

答案 0 :(得分:0)

在模块顶部的子程序之外将颜色长值定义为Const

Public Const bgColorTrue As Long = 13158600  '## RGB(200,200,200)
Public Const bgColorFalse As Long = 16777215 '## RGB(255,255,255)

然后你可以做这样的事情,这有点简化,但仍然需要枚举所有的TextBox + CheckBox。

UserForm2.textbox1.BackColor = IIF(UserForm1.checkbox15.Value = True, bgColorTrue, bgColorFalse)
UserForm2.textbox2.BackColor = IIF(UserForm1.checkbox16.Value = True, bgColorTrue, bgColorFalse)
UserForm2.textbox3.BackColor = IIF(UserForm1.checkbox17.Value = True, bgColorTrue, bgColorFalse)
UserForm2.textbox4.BackColor = IIF(UserForm1.checkbox18.Value = True, bgColorTrue, bgColorFalse)
UserForm2.textbox5.BackColor = IIF(UserForm1.checkbox19.Value = True, bgColorTrue, bgColorFalse)
' etc...

或者(假设复选框和文本框的索引之间的算术关系是常量),你可以做一个循环并创建一个子程序来识别哪个TextBox与CheckBox配对:

Dim cb as MSForms.CheckBox, ctrl as Control
For Each ctrl in UserForm1.Controls
    If TypeName(cb) = "CheckBox" Then
        Call UpdateForm2(cb, UserForm2)
    End If
Next

使用子类:

Sub UpdateForm2(ByRef cb as MSForms.CheckBox, byRef Uf as UserForm)
    Dim tb as MSForms.TextBox
    Dim iCB as Long, iTB as Long
    '## Get the index of this CheckBox name:
    iCB = CLng(Replace(cb.Name, "checkbox", vbNullString))
    '## Compute the index of corresponding TextBox name
    iTB = iCB - 14
    '## Handle the TextBox on the other UserForm
    Set tb = Uf.Controls("TextBox" & iTB)
    tb.BackColor = IIF(cb.Value = True, bgColorTrue, bgColorFalse)
End Sub