VBA Excel使用列表框项填充单个单元格

VBA Excel使用列表框项填充单个单元格,vba,excel,Vba,Excel,如何在VBA中将列表框中的所有项目传递到带有逗号分隔符的单个单元格 这是我当前的代码,我将每个项传递给一个数组,然后将单元格值设置为数组,但它不起作用 Dim histReturn() As Long Dim j As Integer For j = 0 To Me.history_lbx.ListCount - 1 ReDim Preserve histReturn(j) Dim x As Variant

如何在VBA中将列表框中的所有项目传递到带有逗号分隔符的单个单元格

这是我当前的代码,我将每个项传递给一个数组,然后将单元格值设置为数组,但它不起作用

        Dim histReturn() As Long
        Dim j As Integer
        For j = 0 To Me.history_lbx.ListCount - 1
            ReDim Preserve histReturn(j)
        Dim x As Variant
        For Each x In histReturn
            Cells(i, 4).Value = Cells(i, 4).Value & x & ", "
        Next x

如果要使用数组,则不应在循环中重拨,而应一次性重拨,因为您知道维度:
redim histReturn(history.ListCount)
。但是您的数组从未获得任何值,所以当您的第二个循环尝试在其中查找ListBox项时,它无法获得任何值

下面是一个想法,循环获取列表框项目,添加到字符串,然后将结果放入单元格

Dim S As String
If history_lbx.ListCount = 0 Then
    Cells(1, 1).Value = ""
Else
    S = history_lbx.List(0)
    For i = 2 To history_lbx.ListCount
        S = S & ", " & history_lbx.List(i - 1)
    Next i
    Cells(1, 1).Value = S
End If

根本不需要循环。您可以使用
Join
创建逗号分隔的列表,如下所示

Sub Demo
    Dim rng as Range
    Set rng = Cells(1, 1)

    If history_lbx.ListCount = 0 Then
        rng = vbNullString
    Else
        rng = Join(Application.Transpose(history_lbx.List), ",")
    End If
End Sub

此行给出了一个类型不匹配错误:
rng=Join(Application.Transpose(history_lbx),“,”)
edited answer。打字错误,在
应用程序中缺少对
列表的引用。转置(历史记录列表)