VBA代码如何获取多个文件夹路径

问题描述 投票:0回答:1

在Exce上,我想将文件夹的路径存储在一个数组中(我有一个我制作的示例代码),但即使我使用了

.AllowMultiSelect = True
,我也无法选择多个文件夹。有解决办法或者建议吗?

Sub SelectMultipleFolders() 
    Dim selectedFolders As FileDialog 
    Dim folderPath As Variant 
      
    Set selectedFolders = Application.FileDialog(msoFileDialogFolderPicker) 
    selectedFolders.AllowMultiSelect = True 
     
    If selectedFolders.Show = -1 Then 
        For Each folderPath In selectedFolders.SelectedItems 
            MsgBox "Selected Folder: " & folderPath 
        Next folderPath 
    Else 
        MsgBox "Not selected." 
    End If 
End Sub

我想将路径存储在多个变量中。

excel vba select directory
1个回答
0
投票

我不认为可以使用内置文件对话框来完成此操作。 我只能想到一次选择一个,但这是一个非常尴尬的解决方案:

Sub SelectMultipleFolders()
    Dim selectedFolders As FileDialog
    Dim folderPath As String
    Dim folderPaths() As String
    Dim i As Integer
    Dim proceed As Boolean
    
    Set selectedFolders = Application.FileDialog(msoFileDialogFolderPicker)
    
    i = 0
    proceed = True
    
    Do While proceed
        If selectedFolders.Show = -1 Then
            
            ReDim Preserve folderPaths(i)
            folderPaths(i) = selectedFolders.SelectedItems(1)
            MsgBox "Selected Folder: " & folderPaths(i)
            i = i + 1
            
            
            If MsgBox("Do you want to select another folder?", vbYesNo) = vbNo Then
                proceed = False
            End If
        Else
            MsgBox "Folder selection canceled."
            proceed = False
        End If
    Loop
    
    
    If i > 0 Then
        MsgBox "Total folders selected: " & UBound(folderPaths) + 1
        For i = LBound(folderPaths) To UBound(folderPaths)
            MsgBox "Folder " & i + 1 & ": " & folderPaths(i)
        Next i
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.