我希望用户选择他们所选择的文件夹,在用户输入对话框中可以选择路径。
Sub Getsheets()
Path = "D:\Workbooks\" 'want to add the user choice path, rest of code is fine
Filename = Dir(Path & ("*.csv"))
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy after:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
答案 0 :(得分:0)
使用Application.FileDialog
和msoFileDialogFolderPicker
选项(将其限制为选择文件夹)可以轻松实现。
一个简单的例子是:
Sub Getsheets()
Dim Path As String
Path = ""
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then
Path = .SelectedItems(1)
End If
End With
If Path <> "" Then
Filename = Dir(Path & ("\*.csv"))
Do While Filename <> ""
Workbooks.Open Filename:=Path & "\" & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy after:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End If
End Sub
此代码实际上打开了文件夹对话框,并且仅在按下Path
(OK
)时填充.Show = -1
:
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then
Path = .SelectedItems(1)
End If
End With
检查是否选择了Path <> ""
路径。
最后一个小的更改,该路径不包含结尾的反斜杠,因此将其追加:
Filename = Dir(Path & ("\*.csv"))
在OP评论后进行编辑
由于Path
不以反斜杠结尾,因此调用Workbook.Open方法的行上存在错误。固定电话是:
Workbooks.Open Filename:=Path & "\" & Filename, ReadOnly:=True