循环Mac OS X上的文件夹中的文件 – VBA Excel 2011

我试图通过使用VBA Excel 2011在Mac OS X上的文件夹中的文件循环。我尝试了下面的代码,但它不起作用。

Sub ListAllFilesInDir() Dim strFile As String Dim strPath1 As String strPath1 = ActiveWorkbook.FullName MsgBox strPath1 strFile = Dir(strPath1) MsgBox strFile strFile = Dir() MsgBox strFile strFile = Dir() MsgBox strFile End Sub 

当程序到达第一个MsgBox strFile时,我得到活动工作簿的名称。 我读了一些使用Dir而没有参数的地方导致文件夹中的下一个文件。 但是这对我不起作用。 我得到第二个MsgBox strFile命令和一个错误(运行时错误5:无效的过程调用或参数“为第三个MsgBox strFile命令一个空的消息框。我有我试图循环通过文件夹中的4个文件。

另外,我会怎么做只列出“.xslx”文件

这是 dir()函数描述的链接 。 你的问题是,dir(strPath1)将设置dir函数来返回该path中的EXACT文件名的所有实例,这只是一个单一的文件。 如果您希望所有文件以“.xlsx”结尾,请尝试:

 dir(ActiveWorkbook.Path & application.PathSeparator & "*.xlsx") 

此外,如果你有任意数量的文件,你想循环尝试下面的代码。 它工作,因为它返回最后一个文件后,返回一个空string:

 Sub WorkWithFiles() Const PATH = "C:\" Dim file As String file = Dir(PATH & Application.PathSeparator & "*.xlsx") Do Until file = "" 'Run some code on the file in the file variable Debug.Print file 'Then get the next file file = Dir("") Loop End Sub