使用 Excel 宏循环遍历文件夹中的文件
Looping through files in folder with Excel macro
我一直在尝试编写 excel 循环遍历文件夹 returns 文件名中的文件的宏。我一直在谷歌搜索和测试,但我无法让它工作。这是代码:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Set MySource = MyObj.GetFolder("c:\test\")
For Each file In MySource.Files
MsgBox file
Next file
End Sub
我收到此错误:
Run-time error '91':
Object Variable or with block variable not set.
Excel 文件名为 test.xlsm
。文件夹中有 3 个文件:test01.txt
、test02.txt
、test03.txt
。我正在使用 windows 7、64 位。
例如,您需要 Set MyObj
Dim MyObj As Object
Set MyObj = CreateObject("Scripting.FileSystemObject")
否则MyObj
为空变量且returnsNothing
.
使用Dir
function?
Sub LoopThroughFiles()
Dim FileName AS String
FileName = Dir("c:\test\*") 'Any file in the folder
While Len(FileName) > 0
MsgBox FileName 'Say the file's name
FileName = Dir() 'Get next item that matches the filter
Wend
End Sub
我一直在尝试编写 excel 循环遍历文件夹 returns 文件名中的文件的宏。我一直在谷歌搜索和测试,但我无法让它工作。这是代码:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Set MySource = MyObj.GetFolder("c:\test\")
For Each file In MySource.Files
MsgBox file
Next file
End Sub
我收到此错误:
Run-time error '91':
Object Variable or with block variable not set.
Excel 文件名为 test.xlsm
。文件夹中有 3 个文件:test01.txt
、test02.txt
、test03.txt
。我正在使用 windows 7、64 位。
例如,您需要 Set MyObj
Dim MyObj As Object
Set MyObj = CreateObject("Scripting.FileSystemObject")
否则MyObj
为空变量且returnsNothing
.
使用Dir
function?
Sub LoopThroughFiles()
Dim FileName AS String
FileName = Dir("c:\test\*") 'Any file in the folder
While Len(FileName) > 0
MsgBox FileName 'Say the file's name
FileName = Dir() 'Get next item that matches the filter
Wend
End Sub