【问题标题】:Named range in combo box组合框中的命名范围
【发布时间】:2020-06-07 00:18:37
【问题描述】:

如何使用 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

请推荐

【问题讨论】:

  • Def1m 是变量还是命名范围的名称?如果是字符串,则放入“”,例如"Def1m"

标签: excel vba


【解决方案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

【讨论】:

  • @AravindSR - 什么不起作用?如果是某种类型的运行时错误,请尝试将"Def1m" 更改为[Def1m],从而返回一个范围而不是字符串。像这样 - Set .RowSource = [Def1m].
  • 我做到了,但该值未出现在组合框 2 中
  • 您的意思是下拉菜单没有预先填充第一个选项吗?我认为这很正常。您可以使用Combobox2.ListIndex = 0 进行设置。我认为零 (0) 是第一个选项。
【解决方案2】:

您可以创建一个函数,从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

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多