,可以通过以下步骤实现:
Application.FileDialog
对象,可以弹出文件夹选择对话框,让用户选择要访问的文件夹,并获取其路径。Dim folderPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "选择文件夹"
If .Show = -1 Then
folderPath = .SelectedItems(1)
Else
Exit Sub
End If
End With
FileSystemObject
对象,可以遍历指定文件夹中的所有文件,并进行相应操作。Dim fso As Object
Dim folder As Object
Dim file As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderPath)
For Each file In folder.Files
' 对每个文件进行操作,例如导入数据等
Next file
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook ' 当前工作簿
Set ws = wb.Worksheets("Sheet1") ' 目标工作表
For Each file In folder.Files
' 导入文件数据到目标工作表
With ws.QueryTables.Add(Connection:="TEXT;" & file.Path, Destination:=ws.Cells(ws.Rows.Count, 1).End(xlUp).Offset(1, 0))
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True ' 根据实际情况选择分隔符
.Refresh
End With
Next file
以上是使用VBA导入要访问的文件夹中的所有文件的基本步骤。根据实际需求,可以进行相应的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云