通过MFDialogboxFolder加载包含文件夹内容的ListBox

时间:2018-05-25 19:45:25

标签: vba excel-vba excel

我正在尝试通过MFDialogbox Picker加载包含文件夹中文件的列表框。

不幸的是,它不起作用。请求你的帮助。

以下是我正在使用的代码。感谢

我发现'mypath'变量保存了所选文件夹的正确名称。

但是,我发现此后没有任何工作。请帮忙。

Private Sub UserForm_Initialize()

Dim myfiles As String, mypath As String
Dim fileList() As String
    Dim fName As String
    Dim fPath As String
    Dim I As Integer

With Application.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
    If .Show = False Then Exit Sub
    mypath = .SelectedItems(1)
    DoEvents
End With

MsgBox mypath

If Right(mypath, 1) <> "\" Then mypath = mypath & "\"
ReDim fileList(1 To I)

fName = Dir(mypath)
MsgBox fName
    While fName <> ""
         'add fName to the list
        I = I + 1
        ReDim Preserve fileList(1 To I)
        fileList(I) = fName
         'get next filename
        fName = Dir()
    Wend
     'see if any files were found
    If I = 0 Then
        MsgBox "No files found"
        Exit Sub
    End If
     'cycle through the list and add to listbox
    For I = 1 To UBound(fileList)
        Me.ListBox1.AddItem fileList(I)
    Next


End Sub

1 个答案:

答案 0 :(得分:0)

问题是当我到达ReDim fileList(1 To I)时我是0(因为它没有设置)。如果用ReDim fileList(1 To 1)替换它,它应该可以工作。