使用Excel宏循环浏览文件夹中的文件

时间:2019-02-13 16:41:40

标签: excel vba excel-2016

我一直在尝试编写excel宏,该宏循环遍历文件夹中返回文件名的文件。我一直在进行谷歌搜索和测试,但是无法正常工作。这是代码:

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

我收到此错误:

  

运行时错误“ 91”:

     

对象变量或未设置块变量的情况。

Excel文件被命名为test.xlsm。文件夹中有3个文件:test01.txttest02.txttest03.txt。我正在使用Windows 7、64位。

2 个答案:

答案 0 :(得分:3)

例如,您需要Set MyObj

Dim MyObj As Object
Set MyObj = CreateObject("Scripting.FileSystemObject")

否则MyObj是一个空变量,并返回Nothing

答案 1 :(得分:2)

使用Dir function吗?

autoplay=1