我正尝试在VBA中进行编码,以根据图片中所示的所选品牌启用或禁用移动计划的复选框。
如"Y"
或"N"
所示,左侧的表格可用于指示各个品牌的移动方案的可用性。例如,当用户从下拉列表中选择"Apple"
时,只允许他勾选Mobile Plan 1
。
尝试的解决方案仅基于一个标准,在这种情况下,该标准适用于"Apple"
。如何增强编码,以便当用户选择"Samsung"
时,复选框的状态将相应地改变?
我计划将变量声明为Integer
以用作列指示符(例如Apple = 2, Samsung = 3, Nokia = 4
),并将该整数传递给每个函数"CheckBox_Change"
并使用{{ 1}}函数,但出现错误消息:
”过程声明与事件或事件的描述不匹配 具有相同名称的过程”
在我尝试这样做时。
VLOOKUP
答案 0 :(得分:1)
基于@QHarr的答案,您可以减少代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(0, 0) = "G1" Then
Me.CheckBox1.Enabled = (Target = "Apple")
Me.CheckBox2.Enabled = (Target = "Samsung")
Me.CheckBox3.Enabled = (Target = "Samsung")
End If
End Sub
答案 1 :(得分:1)
我会这样(注释中的解释):
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$G$1" Then
With Range("B2:D2").Find(Target.Value, , xlValues, xlWhole) ' reference the cell with the proper Brand
CheckBox1.Enabled = .Offset(1).Value = "Y" 'set checkbox visibility to match referenced cell column corresponding value
CheckBox2.Enabled = .Offset(2).Value = "Y" ' same as above
CheckBox3.Enabled = .Offset(3).Value = "Y" ' same as above
End With
End If
End Sub
您还可以在复选框“索引”之间循环并避免某些代码重复:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$G$1" Then
Dim i As Long
With Range("B2:D2").Find(Target.Value, , xlValues, xlWhole) ' reference the cell with the proper Brand
For i = 1 To 3 ' loop from 1 to 3 (number of checkboxes)
Me.OLEObjects("CheckBox" & i).Enabled = .Offset(i).Value = "Y" 'set current checkbox visibility to match referenced cell column corresponding value
Next
End With
End If
End Sub
答案 2 :(得分:0)
尝试以下方法。它使用Select Case来避免重复代码部分并包含多个子项。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(0, 0) = "G1" Then
Select Case Target.Value
Case "Apple"
Me.CheckBox1.Enabled = True
Me.CheckBox2.Enabled = False
Me.CheckBox3.Enabled = False
Case "Samsung"
Me.CheckBox1.Enabled = False
Me.CheckBox2.Enabled = True
Me.CheckBox3.Enabled = True
Case Else
Me.CheckBox1.Enabled = False
Me.CheckBox2.Enabled = False
Me.CheckBox3.Enabled = False
End Select
End If
End Sub