【问题标题】:Excel VBA - Populating multicolumn userform listbox from array. No data when array has only 1 itemExcel VBA - 从数组填充多列用户表单列表框。数组只有 1 项时没有数据
【发布时间】:2016-09-15 19:29:34
【问题描述】:

我有以下函数,我用它来用数组中的数据填充用户表单列表框:

Function PopulateListboxWithArray(lstbox As MSForms.ListBox, var As Variant)

With lstbox

    If Not IsEmpty(var) Then
    .Clear
        .list = Application.Transpose(var)
        .ListIndex = -1
    End If

End With

End Function

我的列表框包含具有以下属性的两列:

问题

数组中的数据有一个 ID 列和一个 lastname 列。我不希望用户看到 ID 列,所以我在表单中将该列宽度设置为 0。

当我导入多于一行的数据时,数据会按预期显示在列表框中。

但是,当数组只包含一行数据时,列表框显示为空白!

我尝试删除上图中的列宽,当我这样做并重新导入一行数据时,我得到的 ID 和姓氏堆叠在一起。但这当然不是我想要的结果。

我什至尝试用.list = var 替换.list = Application.Transpose(var) 无济于事。

我在这里做错了什么,还是有更好的方法来填充列表框?

干杯

【问题讨论】:

    标签: arrays excel vba listbox


    【解决方案1】:

    我在这篇帖子里找到了答案:Adding item in listbox with multiple columns

    我需要使用.List 属性我的函数现在看起来像这样:

    Function PopulateListboxWithArray(lstbox As MSForms.ListBox, var As Variant)
    
    With lstbox
    
        If Not IsEmpty(var) Then
                .Clear
            If UBound(var, 2) > 0 Then
                .list = Application.Transpose(var)
            Else
                .AddItem var(0, 0)
                .list(.ListCount - 1, 1) = var(1, 0)
            End If
    
        End If
    
    End With
    
    End Function
    

    【讨论】:

      【解决方案2】:

      编辑以添加更多“背景”

      不太清楚你为什么使用 Application.Transpose()

          With lstbox
              If Not IsEmpty(var) Then
                  .Clear
                  If UBound(var, 1) = 1 Then
                      .AddItem
                      .List(0, 0) = var(1, 1)
                      .List(0, 1) = var(1, 2)
                  Else
      '               .List = Application.Transpose(var)
                      .List = var
                  End If
                  .ListIndex = -1
              End If
          End With
      

      我通过以下方式填充var

      Private Sub UserForm_Initialize()
          Dim var As Variant
      
          With Worksheets("LB") '<--| change "LB" to your actual sheet name
              var = .Range("B1", .Cells(.rows.Count, "A").End(xlUp)).Value '<--| populate var with columns "A:B" cells values from row 1 down to column "A" last non empty row
          End With
          With Me.ListBox1
              .ColumnCount = 2 '<--| set listbox columns count
              .ColumnWidths = "0;144" '<--| set listbox columns width
          End With
          PopulateListboxWithArray Me.ListBox1, var
      End Sub
      

      【讨论】:

      • 嗨,感谢您的回复。返回多行数据时需要转置。我确实尝试了 .list = var 但这没有用。欢呼
      • @Nick,不客气。我添加了一些关于如何填充 var 并让它工作的背景
      猜你喜欢
      • 2020-09-17
      • 2018-05-11
      • 2019-11-02
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多