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 For Each x In histReturn Cells(i, 4).Value = Cells(i, 4).Value & x & ", " Next x 

如果你想使用一个数组,你不应该在一个循环中进行REDIMED,但是一劳永逸,因为你知道维度:例如ReDim histReturn(history.ListCount) 。 但是你的数组从来没有得到任何价值,所以当你的第二个循环尝试查找ListBox项目,它不能。

这是一个想法,循环获取ListBox项目,添加到一个string,然后将结果放入一个单元格。

 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来创build逗号分隔列表,如下所示

 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