更改将列表框从垂直添加到水平,并将所有结果加载到列表框中

时间:2016-08-04 10:24:21

标签: excel vba excel-vba listbox

成功将数据加载到列表框后,我被告知数据应该水平定向而不是垂直定向。如何实施新规范?

这是期望的结果:

enter image description here

Private Sub CommandButton3_Click()
    Dim i As Integer
    Dim k As Integer
    With Me.lsbWarenausgang
        For k = 0 To .ListCount - 1
            If .Selected(k) = True Then
                For i = 1 To 9
                    Worksheets("Tabelle5").Cells(i, 1) = Me.lsbWarenausgang.List(k, i - 1)
                Next i
            End If
        Next k
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

使用辅助数组(与列表框列大小相同)填充当前选定的列表框行,然后在excel表中将其写下来

对于后一种操作使用:

  • .Cells(1, .Columns.Count).End(xlToLeft)

    获取第一行中的最后一个非空单元格

  • .Offset(, IIf(IsEmpty(.Cells), 0, 1))

    将其偏移一列,或者不是先前方法返回的范围是否为非空单元格

  • .Resize(9)方法引用与数组具有相同行的1列范围

所以你可以编码:

    Option Explicit

    Private Sub CommandButton3_Click()
        Dim i As Long, k As Long
        Dim arr(1 To 9) As Variant

        With Me.lsbWarenausgang
            For k = 0 To .ListCount - 1
                If .Selected(k) Then
                    For i = 1 To 9
                        arr(i) = .List(k, i - 1)
                    Next i
                    With Worksheets("Tabelle5")
                        With .Cells(1, .Columns.Count).End(xlToLeft)
                            .Offset(, IIf(IsEmpty(.Cells), 0, 1)).Resize(9) = Application.Transpose(arr)
                        End With
                    End With
                End If
            Next k
        End With
    End Sub