【发布时间】:2019-01-29 05:17:20
【问题描述】:
我在为一堆 CSV 文件 (10000) 编写此 VBA 宏时遇到问题。搜索后,我发现/将其用于我的代码: Loop through files in a folder using VBA? 。它似乎不起作用,我不知道为什么......我已经尝试过 While 循环,但它非常慢我不知道它是否可以完成运行。
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("C:\Users\me\Desktop\test")
While (file <> "")
If InStr(file, "test") > 0 Then
'// my macro code is here
Exit Sub
End If
file = Dir
Wend
End Sub
我还应该尝试改变什么?我哪里做错了?我也尝试过使用此代码https://www.thespreadsheetguru.com/the-code-vault/2014/4/23/loop-through-all-excel-files-in-a-given-folder,但我不确定除了目录和'更改第一个工作表的背景填充蓝色之外还有什么要更改的。
还尝试了这个http://www.ozgrid.com/VBA/loop-through.htm,这看起来很简单,但我无法让它工作......
来自 L8N 的更新
Option Explicit
Sub looper()
Dim fso As Scripting.FileSystemObject
Dim aFolder As Scripting.Folder
Dim aFile As Scripting.file
Dim aText As Scripting.TextStreame
Dim singleLine As String
Set fso = New FileSystemObject
Set aFolder = fso.GetFolder("C:\Users\ME\Desktop\test") 'set path to the folder that contains the files
For Each aFile In aFolder.Files 'loops through every file in the top level of the folder
If InStr(1, vbBinaryCompare) > 0 Then
Range("A2:D200210").Clear 'what i want to happen to every file
Set aText = fso.OpenTextFile(aFile.Path, ForReading)
Do Until aText.AtEndOfStream
singleLine = aText.ReadLine 'read line into string, every call advances the line counter by one, this prevents skipping lines
If InStr(1, singleLine, vbBinaryCompare) > 0 Then Debug.Print singleLine ' in line case, prints line if target value is found
Loop
End If
Next aFile
Debug.Print "finished"
结束子
它运行,但似乎没有对每个文件实现我想要的更改 (Range("A2:D200210").Clear )。我的代码的字符串名称也无关紧要,工作表中的信息也不重要。我的原始代码是为了测试它是否循环。
【问题讨论】:
标签: vba excel csv excel-2010