将数据从列表框中检索到范围

时间:2013-06-13 06:40:32

标签: vba

我有一个代码,用于显示用户窗体列表框中范围(A1:E10)的非连续范围

Private Sub UserForm_Initialize()
Dim rng As Range

Set rng = Sheet1.Range("A1:E10")

With ListBox1
  .ColumnCount = 3
  .ColumnWidths = "100;100,100"
  ' load 1st, 3rd and 5th columns of range (A,C and E) into listbox
  .List = Application.Index(rng, Evaluate("ROW(1:" & rng.Rows.Count & ")"), Array(1, 3,5))
End With
End Sub

现在我需要一个单击按钮代码来将列表框中任何选定的行检索到另一个范围(G1:I1)

1 个答案:

答案 0 :(得分:1)

将以下宏分配给该按钮。我正在考虑将您的列表框作为表单控件。  如果是activeX控件,请将 .ListBoxes(“ListBox1”)替换为 .ListBox1 ,然后从 0 开始循环到 .ListCount-1

 Sub Test()

        Dim lngLoop         As Long
        Dim strValue        As String

        With ThisWorkbook.Worksheets("Sheet1")
            With .ListBoxes("ListBox1")
                For lngLoop = 1 To .ListCount
                    If .Selected(lngLoop) Then
                        strValue = strValue & "|" & .List(lngLoop)
                    End If
                Next
           End With
           .Range("G1:I1") = Split(Mid(strValue, 2), "|")
        End With

    End Sub