如何解决VBA代码循环遍历文件夹中的文件
我正在寻找一种方法来自动化在单独的子文件夹中打开1300个单独的Excel文件并对每个文件进行相同更改的过程。更改将是每个文件的同一选项卡上的相同单元格。我几乎完成了代码,但Workbook.open出现了问题,并确保其选择了正确的excel文件。我的代码在下面列出。如果您需要,我还会提供更多信息。感谢您的帮助!
我需要访问的Excel文件位于父文件夹/的子文件夹中 所有需要更新的Excel文件都以List.xlsx
结尾Sub LoopFilesInFolder()
Dim folderName As String
Dim FSOLibrary As FileSystemObject
Dim FSOFolder As Object
Dim FSOFile As Object
'Set the file name to a variable
folderName = "\\net\fs1\users\alex.wood\Desktop\TC Excel Test and Creation Files\VBA TEST FOLDER"
'Set all the references to the FSO Library
Set FSOLibrary = New FileSystemObject
Set FSOFolder = FSOLibrary.GetFolder(folderName)
Set FSOFile = FSOFolder.Files
'Use For Each loop to loop through each file in the folder
For Each FSOFile In FSOFile
Workbooks.Open Filename:=Dir("\\net\fs1\users\alex.wood\Desktop\TC Excel Test and Creation Files\VBA TEST FOLDER\*list*")
Range("G1").Select
ActiveCell.FormulaR1C1 = "New Thin Client"
ActiveWorkbook.Save
ActiveWindow.Close
Next
'Release the memory
Set FSOLibrary = Nothing
Set FSOFolder = Nothing
Set FSOFile = Nothing
End Sub
解决方法
你可以做到
Sub LoopFilesInFolder()
'Improve performance
Application.ScreenUpdating = True
mypath = "\\net\fs1\users\alex.wood\Desktop\TC Excel Test and Creation Files\VBA TEST FOLDER\"
myfile = Dir(mypath & "*.xls*")
Do While myfile <> ""
Workbooks.Open mypath & myfile
Workbooks(myfile).Activate
ActiveSheet.Range("G1").Value = "New Thin Client"
Workbooks(myfile).Save
Workbooks(myfile).Close
myfile = Dir
Loop
Application.ScreenUpdating = False
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。