通过列表框选择项目访问VBA循环并添加到数组

时间:2016-02-17 15:20:17

标签: arrays vba ms-access access-vba listboxitems

我试图遍历列表框并将内容添加到数组....

我的代码是:

Private Sub exportfolders_Click()

Dim list As String
Dim folderlist As String
Dim folderarray() As String
'Dim i As Interger

For i = 0 To Me.selectedfolders.ListCount - 1
    'folderlist = (Me.selectedfolders.Column(0, i))
    'folderarray() = Join(Me.selectedfolders.Column(0, i), ",")
    list = (Me.selectedfolders.Column(0, i))
    folderarray() = Join(list, ",")
    ReDim Preserve folderarray(i)
Next i
   folderlist = folderarray
    'folderarray() = Join(folderlist, ",")
    MsgBox (folderlist)

End Sub

你可以看到我注释掉的位,尝试各种方法让它发挥作用。但我不断收到消息"无法分配给阵列"在folderarray(i) = Join(list, ",")。关于我失败的地方的任何指示?

3 个答案:

答案 0 :(得分:2)

您可以将列表框项连接成一个字符串,然后使用Split()加载您的数组。这样,阵列就可以自动调整大小,而无需ReDim

我在Access 2010中测试了此代码:

Dim folderarray() As String
Dim i As Long
Dim strList As String

For i = 0 To Me!selectedfolders.ListCount - 1
    strList = strList & "," & Me!selectedfolders.Column(0, i)
Next
' use Mid() to exclude the first comma ...
folderarray = Split(Mid(strList, 2), ",")

注意我加载后不知道你想对数组做什么。 MsgBox folderarray会抛出类型不匹配错误。 MsgBox Mid(strList, 2)有效,但如果这是你想要的,你就不需要数组了。

答案 1 :(得分:0)

1)声明数组。看看https://msdn.microsoft.com/en-us/library/wak0wfyt.aspx

2)不需要支持变量

3)使用正确的语法

将值分配给数组
Private Sub exportfolders_Click()

Dim folderarray() As String
Dim i As Interger

Redim folderarray (Me.selectedfolders.ListCount-1)

For i = 0 To Me.selectedfolders.ListCount - 1
    folderarray(i) = Me.selectedfolders.Column(0, i)
Next i

' Write here what you want to do with your array

End Sub

答案 2 :(得分:0)

您可以尝试这样的事情:

Private Sub ListToArray()
    Dim folderArray() As Variant
    Dim currentValue As String
    Dim currentIndex As Integer
    Dim topIndex As Integer

    topIndex = Me.selectedfolders.ListCount - 1
    ReDim folderArray(0 To topIndex, 0 To 1)

    For i = 0 To topIndex
        currentValue = Me.selectedfolders.Column(0, i)
        folderArray(i, 0) = i
        folderArray(i, 1) = currentValue
    Next i
End Sub

注意我的示例是一个多维数组,如果您选择这样做,它将使您能够添加多个项目。在这个例子中,我将“i”的值添加为占位符/索引。