用户表单列表框通过RowSource填充空行

时间:2016-07-19 04:30:56

标签: excel-vba vba excel

我创建了一个ListBox,它应该使用RowSource从另一个工作簿中填充范围,但我得到空行而不是填充列表。 我的空行意味着如果我在我的范围内有8个项目,那么列表在我的列表中有8个空行。 我将代码插入UserForm_Initialize()并使用Workbooks.Open首先打开目标工作簿。

我尝试改变前色,背景色,单元格格式......

Private Sub UserForm_Initialize()

    Dim tmpRange As Range
    'check database file availability then open database
    DstWBName = "\DB.list." & Year(Now) & ".xlsx"
    If Dir(ThisWorkbook.Path & DstWBName) = "" Then GoTo ErrFileNotFound
    SetAttr ThisWorkbook.Path & DstWBName, vbNormal
    Application.ScreenUpdating = False
    Set DstWB = Workbooks.Open(ThisWorkbook.Path & DstWBName, ReadOnly:=False)
    ThisWorkbook.Sheets(1).Activate
    Application.ScreenUpdating = True

    'populate list
    Me.lstCompListBox.RowSource = ""
    Set tmpRange = DstWB.Worksheets(1).Range("B2")
    Set tmpRange = Range(tmpRange, tmpRange.End(xlDown))
    Me.lstCompListBox.RowSource = tmpRange.Address
    'Me.lstCompListBox.AddItem "test123"
    '.additem work but not the rowsource

    Exit Sub

    'error handle for missing file
ErrFileNotFound:
    MsgBox ThisWorkbook.Path & DstWBName & " Not Found!"
    Unload Me
End Sub

我的编码年龄为1周,请帮助我处理凌乱的代码。

我的Userform有空行 enter image description here

1 个答案:

答案 0 :(得分:1)

尝试更改行

Me.lstCompListBox.RowSource = tmpRange.Address

Me.lstCompListBox.RowSource = tmpRange.Address(external:=True)  

这背后的原因是您从外部工作簿加载数据,这样您就不能简单地使用范围地址,如B2:B6,因为这仍然是指您当地的WB。使用external:=True,返回的地址将完全限定文件,工作表和数据的范围地址。