将动态行分配给Listbox

时间:2017-10-22 15:25:07

标签: excel vba userform

我在“Sheet1”上的列“A”上有动态行,这些行正在从10行更改为60行。我有这个代码将这些行填充到我的Userform列表框中,并带有选项选项(在“工作表2”中工作时)。我无法弄清楚问题出在哪里? :(

2)如果让我知道,我将非常感激:如何隐藏“工作表2”中“B”行上的列与我的列表框中的共同选择项目? 以下是截图:

Q1 Q2

希望有意义。 感谢

Option Explicit

Private Sub UserForm_Initialize()
    Dim ColCnt As Long
    Dim rng As Range
    Dim ColWidths As String
    Dim i As Long


    With ThisWorkbook.Sheets("Sheet1")
    Set rng = Range("A1", .Range("A2").End(xlDown))
    End With

        With Me.lbxRange
        .ColumnCount = 1
        .RowSource = rng.Offset(5).Resize(rng.Rows.Count - 1).Address
    End With
End Sub

2 个答案:

答案 0 :(得分:0)

在设计模式下,清除 ListBox的 RowSource 属性并尝试使用以下代码...

Private Sub UserForm_Initialize()
    Dim i As Long, j As Long, LR As Long
    Dim x()
    With ThisWorkbook.Sheets("Sheet1")
        LR = .Cells(Rows.Count, 1).End(xlUp).Row
        For i = 2 To LR
            If VBA.Trim(.Cells(i, 1)) Like "?*" Then
                j = j + 1
                ReDim Preserve x(1 To j)
                x(j) = .Cells(i, 1)
            End If
        Next i
        If j > 0 Then
        Me.lbxRange.List = x
        Else
        Me.lbxRange.Clear
        End If
    End With
End Sub

删除未使用的变量,如果稍后在同一事件中使用它们,请添加它们。

答案 1 :(得分:0)

@stkneer:老实说,我无法解决这个问题。这是我第一次查询并正常工作的代码。对于第二个查询(隐藏列),我将其发布到新线程中。再次感谢

Private Sub UserForm_Initialize()

    Dim r As Range
    Dim DataArea As Range
      Application.ScreenUpdating = False

    Sheets("Sheet1").Select
    Range("a2").Select
    Set DataArea = Range("a2", Range("a2").End(xlDown))

     For Each r In DataArea
        lstBox1.AddItem r.Value
    Next r

    lstBox1.MultiSelect = fmMultiSelectMulti
    lstBox1.ListStyle = fmListStyleOption

    Sheets("Sheet2").Select
    Application.ScreenUpdating = True
End Sub