我的用户表单为用户提供了3种颜色[红色,绿色,蓝色]的“高值”和“低值”选项。但是,用户必须为每种颜色选择一种颜色,当然不能为高值和低值选择相同的颜色。颜色突出显示数据中的低值和高值,以区分它们。我附上了我的用户表单和我的代码部分的图片,我无法为其分配不同颜色的不同颜色。任何有关如何纠正我的IF逻辑的帮助将不胜感激。
Public Function ShowInputsDialog(LowColor As Long, HighValue As Single, HighColor As Long, LowValue As Single)
Call Initialize
Me.Show
If Not Cancel Then
If optRed1.Value Then '<-- Assigning the 3 colors to the Low Values
LowColor = vbRed
ElseIf optGreen1.Value Then
LowColor = vbGreen
Else
LowColor = vbBlue
End If
If optRed2.Value Then HighColor = vbRed '<-- Assigning the 3 colors to the High Values
ElseIf optGreen2.Value Then HighColor = vbGreen
Else
HighColor = vbBlue
End If
End If
HighValue = txtHigher.Value
LowValue = txtLower.Value
ShowInputsDialog = Not Cancel
Unload Me
End Function
答案 0 :(得分:2)
我要点如下:
为每个单选按钮添加BeforeUpdate()
个事件
让事件处理程序让控件假设用户输入值,如果兼容与其对应的&#34;控制一个
这个,通过一个sub来检查活动控制值与其对应的&#34;一个
Private Sub optBlue1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub optBlue2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub OptGreen1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub OptGreen2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub OptRed1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub OptRed2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
CrossCheck
End Sub
Private Sub CrossCheck()
Dim optNr As String, optName As String
With Me
If .ActiveControl.ActiveControl.Value Then
optName = .ActiveControl.ActiveControl.name
optNr = Mid(optName, Len(optName), 1)
.ActiveControl.ActiveControl.Value = Not (.ActiveControl.ActiveControl.Value = .Controls(Replace(optName, optNr, IIf(optNr = "1", "2", "1"))).Value)
End If
End With
End Sub
当然,Class
方法可以减轻编写所有Private Sub optXXXX_BeforeUpdate()
事件处理程序的负担,并为当前编码和未来代码增强提供更大的灵活性,但如果您坚持只有三个单选按钮可能有点矫枉过正
BTW以上所有内容意味着您的ShowInputsDialog()
sub不必关心选项按钮兼容性,并且可以执行其简单的值分配工作,我为此&# 39; d使用Select Case语法而不是If Then - Else If Then - End If
语法:
If Not Cancel Then
Select Case True
Case OptRed1.Value
LowColor = vbRed
Case OptGreen1.Value
LowColor = vbGreen
Case Else
LowColor = vbBlue
End Select
Select Case True
Case OptRed2.Value
HighColor = vbRed
Case OptGreen2.Value
HighColor = vbGreen
Case Else
HighColor = vbBlue
End Select
End If
或者您可以使用辅助函数:
Function GetColor(opt1 As MSForms.OptionButton, opt2 As MSForms.OptionButton) As Long
Select Case True
Case opt1.Value
GetColor = vbRed
Case opt2.Value
GetColor = vbGreen
Case Else
GetColor = vbBlue
End Select
End Function
然后简单地写
If Not Cancel Then
LowColor = GetColor(OptRed1, OptGreen1)
HighColor = GetColor(OptRed2, OptGreen2)
End If