首页 > 解决方案 > 循环遍历文件夹中未知数量的文件

问题描述

我有一个包含 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

标签: excelvbafor-loop

解决方案


你可以试试这个简单的代码:

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

推荐阅读