我有一个包含10个Excel文件的文件夹+ 1个包含宏的文件。我只打开宏。如何获取位于宏文件(使用vba)的文件夹中的所有其他文件的列表以及如何逐个打开和关闭它们?
答案 0 :(得分:1)
这可以让你走上正轨。这些宏将遍历文件夹并打开或关闭文件夹中的所有文件。
Sub LoopThroughFilesAndOpen()
Dim strFile As String
Dim strPath As String
Dim colFiles As New Collection
Dim i As Integer
strPath = "put your directory here"
strFile = Dir(strPath)
While strFile <> ""
colFiles.Add strFile
strFile = Dir
Wend
'List filenames in Column A of the active sheet
If colFiles.Count > 0 Then
For i = 1 To colFiles.Count
ActiveSheet.Cells(i, 1).Value = colFiles(i)
Workbooks.Open Filename:=strPath & colFiles(i)
Next i
End If
End Sub
Sub LoopThroughFilesAndClose()
Dim strFile As String
Dim strPath As String
Dim colFiles As New Collection
Dim i As Integer
strPath = "put your directory here"
strFile = Dir(strPath)
While strFile <> ""
colFiles.Add strFile
strFile = Dir
Wend
'List filenames in Column A of the active sheet
If colFiles.Count > 0 Then
For i = 1 To colFiles.Count
ActiveSheet.Cells(i, 1).Value = colFiles(i)
'Workbooks.Close Filename:=strPath & colFiles(i)
Workbooks(colFiles(i)).Close SaveChanges:=False
Next i
End If
End Sub
祝你好运。 - 只需放入你想要的直接电源,例如 - “C:\ myfolder \”
EDIT / ADDITION:
如果您希望宏自动使用活动工作簿的直接指向(运行宏的工作簿),那么您可以使用上述宏的这些版本:
Sub LoopThroughFilesAndOpen()
Dim strFile As String
Dim strPath As String
Dim colFiles As New Collection
Dim i As Integer
strPath = ActiveWorkbook.Path & "\"
strFile = Dir(strPath)
While strFile <> ""
colFiles.Add strFile
strFile = Dir
Wend
'List filenames in Column A of the active sheet
If colFiles.Count > 0 Then
For i = 1 To colFiles.Count
ActiveSheet.Cells(i, 1).Value = colFiles(i)
Workbooks.Open Filename:=strPath & colFiles(i)
Next i
End If
End Sub
Sub LoopThroughFilesAndClose()
Dim strFile As String
Dim strPath As String
Dim colFiles As New Collection
Dim i As Integer
strPath = ActiveWorkbook.Path & "\"
strFile = Dir(strPath)
While strFile <> ""
colFiles.Add strFile
strFile = Dir
Wend
'List filenames in Column A of the active sheet
If colFiles.Count > 0 Then
For i = 1 To colFiles.Count
ActiveSheet.Cells(i, 1).Value = colFiles(i)
'Workbooks.Close Filename:=strPath & colFiles(i)
Workbooks(colFiles(i)).Close SaveChanges:=False
Next i
End If
End Sub
这改变了这一行:
strPath = "put your directory here"
要:
strPath = ActiveWorkbook.Path & "\"
注意:
这两个宏是从以下角度拍摄和修改的: http://www.vadriano.com/excel-vb/2007/04/21/how-to-loop-through-files-in-a-folder/