【问题标题】:excel vba columns to listboxexcel vba列到列表框
【发布时间】:2016-12-18 01:42:08
【问题描述】:

我希望使用表格 1 第 1 行中的值填充 Excel VBA 用户表单列表框,表格中的列数是动态的(列的范围可以在 22 到 30 列之间)。

到目前为止,我有以下代码,但它只填充列表框中单元格“A1”的值。

Dim rngSource As Range
Dim lCol As Long

'Determine last column
lCol = Cells(1, Columns.Count).End(xlToLeft).Column

'Set range source data to be included in listbox
Set rngSource = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, lCol))

'Populate listbox with range source data
lstAllFields.List = rngSource.Cells.Value

感谢您的帮助。

【问题讨论】:

    标签: excel listbox vba


    【解决方案1】:

    改变你的陈述

    ListBox1.List = rngSource.Cells.Value
    

    成为

    ListBox1.List = Application.Transpose(rngSource.Cells.Value)
    

    以便将单元格视为一列值而不是一行值。


    正如 A.S.H 在评论中指出的那样,您还具有不合格的属性(即 Cells 之类的东西,您没有指定该属性所指的工作表,因此它默认为活动工作表)。一旦您开始需要在宏中使用多个工作表,这些可能会导致问题,因此最好现在就养成完全限定事物的习惯。

    目前,您的代码(在我上面建议的更正之后)相当于:

    Dim rngSource As Range
    Dim lCol As Long
    
    'Determine last column
    lCol = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
    
    'Set range source data to be included in listbox
    Set rngSource = Worksheets("Sheet1").Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(1, lCol))
    
    'Populate listbox with range source data
    lstAllFields.List = Application.Transpose(rngSource.Cells.Value)
    

    使用属于ActiveSheetCells 作为Worksheets("Sheet1") 上的Range 的边界可以正常工作,而ActiveSheetWorksheets("Sheet1") 是相同的,但如果它们不同则会崩溃。

    我建议使用With Worksheets("Sheet1") 块,它只允许我们在语法上将所有出现的Worksheets("Sheet1") 简化为.。您的代码将如下所示:

    Dim rngSource As Range
    Dim lCol As Long
    
    With Worksheets("Sheet1")    
        'Determine last column
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    
        'Set range source data to be included in listbox
        Set rngSource = .Range(.Cells(1, 1), .Cells(1, lCol))
    
        'Populate listbox with range source data
        lstAllFields.List = Application.Transpose(rngSource.Cells.Value)
    End With
    

    【讨论】:

    • @A.S.H - 你一定一直在看我!我发布了更新,然后我去支持你的评论,但它已经消失了。
    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多