简体   繁体   中英

excel vba columns to listbox

I'm looking to populate an Excel VBA userform listbox with values from Sheet 1, Row 1 with a dynamic number of columns in the sheet (columns can range between 22 and 30 columns).

So far I have the following code, but it only populates the value of cell "A1" in the listbox.

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

Thanks for the assistance.

Change your statement which says

ListBox1.List = rngSource.Cells.Value

to be

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

so that the cells are treated as if they were a column of values instead of a row of values.


As pointed out in a comment by ASH, you also have unqualified properties (ie things like Cells where you don't specify which worksheet that the property is referring to, and therefore it defaults to the active sheet). These can cause problems as soon as you start needing to use more than one worksheet in your macro, so it is better to get into the habit of fully qualifying things now.

At the moment, your code (after my suggested correction above) is equivalent to:

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)

The use of Cells belonging to the ActiveSheet as the bounds for a Range on Worksheets("Sheet1") works fine while ActiveSheet and Worksheets("Sheet1") are the same thing, but will crash if they are different.

I would recommend the use of a With Worksheets("Sheet1") block, which just allows us to syntactically shortcut all occurrences of Worksheets("Sheet1") to simply . . Your code would then look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM