如何使用VBA在组合框中插入命名范围 在这里,根据combobox1中的值,我需要在combobox2中插入某些命名范围。 这里的Def1m,Def2m等是命名范围
Private Sub Def_Change()
If combobox1.Value = "1 month" Then
Me.combobox2.RowSource = Def1m
ElseIf combobox1.Value = "2 month" Then
Me.combobox2.RowSource = Def2m
ElseIf combobox1.Value = "3 month" Then
Me.combobox2.RowSource = Def3m
ElseIf combobox1.Value = "6 month" Then
Me.combobox2.RowSource = Def6m
ElseIf combobox1.Value = "yearly" Then
Me.combobox2.RowSource = Defyearly
End If
End Sub
请提出建议
答案 0 :(得分:1)
在将字符串写入属性时,需要将数据用引号引起来,因此要将RowSource设置为Def1m,您将发送“ Def1m”(作为字符串)。
此外,您最好使用Select Case
语句来使其整洁:
Private Sub Def_Change()
With Me.combobox2
Select Case combobox1.Value
Case "1 month": .RowSource = "Def1m"
Case "2 month": .RowSource = "Def2m"
Case "3 month": .RowSource = "Def3m"
Case "6 month": .RowSource = "Def6m"
Case "yearly": .RowSource = "Defyearly"
End Select
End With
End Sub
答案 1 :(得分:0)
您可以创建一个函数,从combobox1
中获取字符串并返回一个范围。因此,您可以像这样调用该函数:
Me.combobox2.RowSource = GetRowSource(combobox1.Value)
整个逻辑将变得整洁:
Sub TestMe()
Debug.Print GetRowSource("2 month").Address 'prints the address of named range "Def2m"
End Sub
Public Function GetRowSource(timePeriod As String) As Range
Select Case timePeriod
Case "1 month"
Set GetRowSource = [Def1m]
Case "2 month"
Set GetRowSource = [Def2m]
Case "3 month"
Set GetRowSource = [Def3m]
Case "6 month"
Set GetRowSource = [Def6m]
Case "yearly"
Set GetRowSource = [Defyearly]
Case Else
Set GetRowSource = Nothing
End Select
End Function