Userform listbox rowsource not populating

2019-07-25 05:44发布

问题:

I have a userform with an OK and Cancel button and a listbox. It is supposed to populate using this code:

Private Sub UserForm_Initialize()

Me.StartUpPosition = 0
Me.Top = Application.Top + (Application.Height / 2) - (Me.Height / 2)
Me.Left = Application.Left + (Application.Width / 2) - (Me.Width / 2)

With Me.ListBox1
    .RowSource = ""
    .ColumnCount = 7
    .ColumnWidths = "80;100;20;1;20;1;1000"
    .RowSource = Sheets("BOH Database").Range("H9:N14").Address
  '  .RowSource = Sheets("BOH Database").Range("H9:N" & Sheets("BOH Database").Range("a65536").End(xlUp).Row - 1).Address
End With

End Sub

Neither RowSource statements work. I have tried clearing RowSource before filling it again. What am I doing wrong?

EDIT: I've added the code i currently have here as it doesn't show properly in the comment: I'm using this code based on yours and it's crashing the sheet:

With Me.ListBox1
 .ColumnCount = 7
 .ColumnWidths = "80;100;20;1;20;1;1000"
 .RowSource = "'" & Sheets("BOH Database").Name & "'!" & Sheets("BOH Database") _
    .Range("H9:N" & Sheets("BOH Database").Range("a65536").End(xlUp).Row - 1).Address
End With

回答1:

That is an incorrect way to do it. The syntax is

ListBox1.RowSource = "SheetName!RangeAddress"

So if your sheet name is say Sheet1 then the above becomes

ListBox1.RowSource = "Sheet1!H9:N14"

Also since your sheet name has a space, you will have to add ' before and after the sheet name.

Try this

 ListBox1.RowSource = "'BOH Database'!H9:N14"

Or in your way...

With Sheets("BOH Database")
    ListBox1.RowSource = "'" & .Name & "'!" & .Range("H9:N14").Address
End With


回答2:

How about this.

Sub lbxChange () 
    Dim sname as string 
    Dim ws as worksheet 
    Set sname = combobox1.value 
    Set ws = sheets(sname) 
    Listbox1.rowsource = ws.range("a1:d10") 
End sub

Not work !!!!