首页 > 解决方案 > 循环文件以查找特定文件

问题描述

我正在尝试设置一个宏,您可以在其中打开具有特定名称的某些文件,而无需浏览我已经过滤过的文件。

在此宏之前的代码中,它遍历整个文件夹,打开所有符合条件的文件,从那里提取一个数字,粘贴到新工作簿中,关闭该工作簿,然后转到下一个文件。

我在当前工作簿的某个范围内有条件,并且我想在确定要在文件夹中打开哪些工作簿时使用该条件。

我想知道是否有一种方法可以从之前使用宏打开的最后一个文件开始循环遍历文件夹。

编辑:以下代码是我到目前为止所拥有的。

Sub LoopThroughFilesInFolder()

'=============================================================================
'Looping through all of the files in the folder, and grabbing the last value
'=============================================================================

Dim wb As Workbook
Dim MyPath As String
Dim MyFile As String
Dim myExtension As String
Dim FolderPicker As FileDialog

Application.ScreenUpdating = False

'Retrieve Target Folder Path From User
Set FolderPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FolderPicker
    .Title = "Select a Target Folder"
    .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    MyPath = .SelectedItems(1) & "\"
End With

'In case of cancel
NextCode:
    MyPath = MyPath
    If MyPath = "" Then GoTo ResetSettings

'Target File Extension
myExtension = "*1*9 Restraint*.xls*"

'Target Path with Ending Extension
MyFile = Dir(MyPath & myExtension)

'Loop through each Excel file in folder
LastRow = Sheets("Sheet Name").Cells(Rows.Count, 1).End(xlUp).Row
i = LastRow - 1
Do While MyFile <> ""
    If MyFile Like Cells(LastRow, 1).Value Then
        Set wb = Workbooks.Open(Filename:=MyPath & MyFile, ReadOnly:=True)
        'Ensure Workbook has opened before moving on
        DoEvents

        'Find last row
        LastRow = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
        'Grab value next to last row
        LastValue = ActiveSheet.Cells(LastRow, 2).Value
        If WorksheetFunction.IsNumber(LastValue) = False Then
            LastValue = ActiveSheet.Cells(LastRow, 3).Value
        End If

        'Go back to graph workbook
        Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 2).Value = MyFile
        Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 3).Value = LastValue
        i = i + 1
        wb.Close savechanges:=False
        DoEvents
        MyFile = Dir
    End If
Loop

'Reset Macro Optimization Settings
ResetSettings:
    Application.EnableEvents = True
    Application.ScreenUpdating = True


End Sub

这是遍历整个文件夹(大约有 1000 个文件)。我上面的问题假设我们已经完成了这个宏,并且我当前正在尝试编写的宏只会打开符合特定条件的最新文件,尽管仍然来自同一个文件夹(但不必遍历那些已经从上一个宏打开)。

标签: excelvba

解决方案


没有新文件模式的 Dir$() 检索下一个匹配文件 (Win32 FindNextFile),而 Dir$(file pattern) 重新开始搜索,即使模式与前一个相同 (Win32 FindFirstFile)。

话虽这么说,也许做类似的事情

Static bolBeenHere As Boolean

If bolBeenHere = False Then
' First search, use the file search pattern
   ' Target Path with Ending Extension
   MyFile = Dir(MyPath & myExtension)
   bolBeenHere = True
Else
' Retrieve the next matching file
   MyFile = Dir$()
End If

' Stuff
Do While MyFile <> ""
...
Loop

一个小的性能建议。利用

Do While Len(MyFile) > 0

代替

Do While MyFile <> ""

字符串比较比数字比较“花费”更多。


推荐阅读