我有一个组合框( GSMListType ),其中包含不同的变量“A”,“A - K”,“B”,“C”,< / strong> etc ...链接到列表框( AvailableNumberList ),它根据组合框中的选择调用来自不同工作表的单元格。 组合框有32个不同的变量,可以调用32个不同的工作表。以下是代码示例。
有没有办法简化下面提到的代码?工作表功能齐全,但代码很乱。
Private Sub GSMListType_Change()
Dim TypeLookup As Double
'If listing has changed, clear AvailableNumberList and insert new data
If GSMListType.ListIndex > -1 Then
AvailableNumberList.Clear
If GSMListType.Value = "A" Then
TypeLookup = Application.WorksheetFunction.CountIf(A_Regular.Range("A:E"), GSMListType.Value)
With AvailableNumberList
For k = 2 To TypeLookup + 1
.AddItem A_Regular.Range("A" & k).Value
Next k
End With
ElseIf GSMListType.Value = "A - K" Then
TypeLookup = Application.WorksheetFunction.CountIf(A_K.Range("A:E"), GSMListType.Value)
With AvailableNumberList
For k = 2 To TypeLookup + 1
.AddItem A_K.Range("A" & k).Value
Next k
End With
ElseIf GSMListType.Value = "B" Then
TypeLookup = Application.WorksheetFunction.CountIf(B_Regular.Range("A:E"), GSMListType.Value)
With AvailableNumberList
For k = 2 To TypeLookup + 1
.AddItem B_Regular.Range("A" & k).Value
Next k
End With
ElseIf GSMListType.Value = "C" Then
TypeLookup = Application.WorksheetFunction.CountIf(C_Regular.Range("A:E"), GSMListType.Value)
With AvailableNumberList
For k = 2 To TypeLookup + 1
.AddItem C_Regular.Range("A" & k).Value
Next k
.
.
.
End With
End If
End If
End Sub
答案 0 :(得分:1)
我认为这不会通过任何实质性措施改进您的原始代码示例,但它通过减少重复部分来实现整洁。
Private Sub GSMListType_Change()
Dim TypeLookup As Long, ws As Worksheet
'If listing has changed, clear AvailableNumberList and insert new data
If GSMListType.ListIndex > -1 Then
With GSMListType
Select Case .Value
Case "A"
Set ws = A_Regular 'Sheets("A_Regular") ?????
Case "A - K"
Set ws = A_K
Case "B"
Set ws = B_Regular
Case "C"
Set ws = C_Regular
Case Else
'do nothing
End Select
TypeLookup = Application.CountIf(ws.Range("A:E"), .Value)
End With
With AvailableNumberList
.Clear
For k = 2 To TypeLookup + 1
.AddItem ws.Range("A" & k).Value
Next k
End With
End If
Set ws = Nothing
End Sub
我不确定您的工作表指定方法是指向各种工作表的某个模块范围的变量,因此我包含了一个使用工作表名称的注释替代方法。