循环浏览文件以查找特定文件

时间:2019-07-16 21:06:14

标签: excel vba

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

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

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

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

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

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个文件)。上面的问题是假设我们已经完成了该宏,而我当前要编写的宏将只打开符合特定条件的最新文件,尽管这些文件仍来自同一文件夹(但不必循环通过已从上一个宏打开)。

1 个答案:

答案 0 :(得分:0)

没有新文件模式的

Dir $()会检索下一个匹配文件(Win32 FindNextFile),而Dir $(文件模式)会重新开始搜索,即使该模式与上一个文件相同(Win32 FindFirstFile)

话虽如此,也许做类似的事情

Static bolBeenHere As Boolean

If bolBeenHere Is 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 <> ""

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