我正在尝试使用 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
的空消息框命令和第三个 MsgBox strFile
命令的错误(运行时错误 5:无效的过程调用或参数)。我试图循环遍历的文件夹中有 4 个文件。另外,我会怎么做才能只列出“.xslx”文件
最佳答案
Here's a link到 dir() 函数的描述。您的问题是 dir(strPath1) 将设置 dir 函数以返回该路径中该 EXACT 文件名的所有实例,该路径只会是一个文件。如果您想要所有以“.xlsx”结尾的文件,请尝试:
dir(ActiveWorkbook.Path & application.PathSeparator & "*.xlsx")
此外,如果您有任意数量的文件要循环,请尝试以下代码。它之所以有效,是因为 dir 在返回最后一个文件后返回一个空字符串:
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
关于excel - 在 Mac OS X 上循环浏览文件夹中的文件 - VBA Excel 2011,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294838/