2014-03-29 179 views
1

如何使用VBA中的逗號分隔符將列表框中的所有項目傳遞給單個單元格?VBA Excel使用列表框項目填充單元格

這是我當前的代碼,我將每個項目傳遞給一個數組,然後將單元格值設置爲數組,但它不起作用。

 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 

回答

1

如果你想使用一個數組,你不應該在一個循環中REDIM,但一勞永逸,因爲你知道尺寸:ReDim histReturn(history.ListCount)例如。但是你的數組從來沒有得到任何價值,所以當你的第二個循環嘗試在其中查找ListBox項時,它不能。

這是一個想法,循環獲取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 
+0

明白了,謝謝你的解釋。 – webhead

2

根本沒有必要循環。你可以使用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 
+0

此行給出類型不匹配錯誤: 'rng = Join(Application.Transpose(history_lbx),「,」)' – webhead

+0

編輯答案。錯字,缺少對'Application.Transpose(history_lbx.List)'中'List'的引用 –