excel - 循环遍历文件夹中未知数量的文件
问题描述
我有一个包含 Excel 文件的文件夹,其名称格式为“file_”& Date &_”& i &“.xls”,其中 i 是 1 到 5 之间的整数。
根据日期,文件夹中可能有 1 到 5 个文件:
file_01.01.2019_1.xls
file_02.01.2019_1.xls
file_02.01.2019_2.xls
file_03.01.2019_1.xls
file_03.01.2019_2.xls
file_03.01.2019_3.xls
我想提供一个日期,比如说 1 月 2 日,然后在 for 循环中打开该日期的所有文件。但是,我不能给 i 一个固定的上限值。
如果我知道每个日期的文件数,它将如下所示:
Dim Date As Date
Date = 02.01.2019
For j = 1 To i
Workbooks.Open "path" & "file_" & Date & "_" & j & ".xls"
Copy and Paste Operations to another Workbook here
Workbooks("file_" & Date & "_" & j & ".xls").Close SaveChenges:=False
Next
解决方案
你可以试试这个简单的代码:
Sub OpenFile()
Dim dt As String
dt = "02.01.2019"
Dim fileNameStart As String
fileNameStart = "file_" & dt & "_"
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Dim oPath As String
sPath = "path to your folder, with \ at the end"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Sub
For Each oFile In oFiles
If InStr(1, oFile.Name, fileNameStart) = 1 Then Workbooks.Open sPath & oFile.Name
Next
End Sub
推荐阅读
- javascript - 防止运行 setTimeout 的递归函数复合
- web - Apple 使用什么语言来开发其网站?
- automation - 在进行水平滚动时从网格列中获取文本
- css - 使材质 UI 抽屉保持相同大小,而不是在内容大小更改时调整大小
- java - Android错误:读取bufferedreader后连接被重置
- flutter - VSCode 找不到 Flutter SDK 的路径
- angular - 无法读取未定义 Angular 8 的属性“本机元素”
- javascript - 如何在 Ionic 3 中使用 cordova-plugin-android-permissions 来访问默认的短信应用程序 android?
- go - 有什么方法可以在 exec.Command 中执行多个命令?
- wordpress - 如何将域名指向 VPS/专用服务器