如果 VBA 中的函数如何循环

how loop if function in VBA

如何在 vba 代码中重复 if 函数 您好,我在表单上使用 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 ...

将您的颜色长值定义为 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...

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

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