【发布时间】:2019-07-16 21:06:14
【问题描述】:
我正在尝试设置一个宏,您可以在其中打开具有特定名称的某些文件,而无需浏览我已经过滤过的文件。
在此宏之前的代码中,它循环遍历整个文件夹,打开所有符合条件的文件,从中提取一个数字,粘贴到新工作簿中,关闭该工作簿,然后转到下一个文件.
我在当前工作簿的某个范围内有条件,我想在确定要在文件夹中打开哪些工作簿时使用该条件。
我想知道是否有办法从之前使用宏打开的最后一个文件开始循环遍历文件夹。
编辑:以下代码是我目前所拥有的。
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 个文件)。我上面的问题假设我们已经完成了这个宏,并且我当前正在尝试编写的宏只会打开符合特定条件的最新文件,但仍然来自同一个文件夹(但不必遍历那些已从上一个宏打开)。
【问题讨论】:
-
可能。请edit你的问题与你目前的代码,它会更容易帮助你,谢谢!
-
如果您更改了条件,您不想重新开始吗?
-
你不会有一个更高阶的
For循环来维持你在文件夹中文件的流动..?