代码之家  ›  专栏  ›  技术社区  ›  Samuel Hulla

如何正确地将参数传递给rowsource?

  •  0
  • Samuel Hulla  · 技术社区  · 6 年前

    我有一个 Combobox 我正试图从表的标题行向其传递参数。

    问题是,出于某种原因,我 组合框 似乎只显示第一个结果,尽管逻辑上它不应该。

    这是我的数据,范围从 B2:J2 (问题是它是动态的,所以我 不能就这么过去 Properties

    enter image description here

    在激活我的 UserForm 我尝试获取表的长度(因为它是动态的,可以在 户窗体 激活)

    Private Sub UserForm_Activate()
        Dim res As String
        Dim cell As Range: Set cell = Sheets("Pomocne").Range("B2")
        Dim endcell As Range
        Do Until IsEmpty(cell)
            Set endcell = cell
            Set cell = cell.Offset(0, 1)
        Loop
    
        res = "Pomocne!B2:" & Replace(endcell.address, "$", "")
        obor_combo.RowSource = res
    
        Debug.Print res
    End Sub
    

    现在,一切似乎都很顺利, Debug.print res 产生以下结果:

    enter image description here

    这正是我要传递的 obor_combo.RowSource = res 然而。当我检查实际的 户窗体 不知什么原因,它似乎只显示了第一个结果。

    知道是什么原因吗?

    enter image description here

    0 回复  |  直到 6 年前
        1
  •  1
  •   DisplayName    6 年前

    RowSource 是为 柱状的 范围:如果将其指定为 行状 范围你只能得到第一个单元格

    但你可以用 List 性质 ComboBox 对象,并用通过 行状 范围:

    Private Sub UserForm_Activate()
        Dim res As String
        Dim cell As Range: Set cell = Sheets("Pomocne").Range("B2")
        Dim endcell As Range
        Do Until IsEmpty(cell)
            Set endcell = cell
            Set cell = cell.Offset(0, 1)
        Loop
    
        res = "Pomocne!B2:" & Replace(endcell.Address, "$", "")
        obor_combo.List = Application.Transpose(Range(res).Value)    
    End Sub
    

    可以简化为:

    Private Sub UserForm_Activate()    
        With Sheets("Pomocne")
            obor_combo.List = Application.Transpose(.Range("B2", .Cells(2, .Columns.Count).End(xlToLeft)).Value)
        End With
    End Sub