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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7294838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 13:57:43  来源:igfitidea点击:

Loop though files in a Folder on Mac OS X - VBA Excel 2011

macosexcelvbaexcel-vbaexcel-vba-mac

提问by Curious2learn

I am trying to loop through files in a folder on Mac OS X using VBA Excel 2011. I tried the following code, but it does not work.

我正在尝试使用 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

I get the name of the active workbook when the program reaches the first MsgBox strFile. I read somewhere that using Dirwithout an argument results in the next file in the folder. But that does not work for me. I get an empty message box for the second MsgBox strFilecommand and an error (Runtime error 5: Invalid Procedure call or argument" for the third MsgBox strFilecommand. I have 4 files in the folder that I am trying to loop through.

当程序到达第一个MsgBox strFile. 我在某处读到Dir没有参数使用会导致文件夹中的下一个文件。但这对我不起作用。我收到第二个MsgBox strFile命令的空消息框和第三个命令的错误(运行时错误 5:无效的过程调用或参数” MsgBox strFile。我正在尝试循环的文件夹中有 4 个文件。

Also, what would I do to list only ".xslx" files

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

回答by Banjoe

Here's a linkto a description of the dir() function. Your issue is that dir(strPath1) will set the dir function to return all instances of that EXACT filename in that path, which is only ever going to be a single file. If you'd like all files ending in ".xlsx" try:

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

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

Also, if you have an arbitrary number of files you want to loop through try the following code. It works becuase dir returns an empty string after it's returned the last file:

此外,如果您想要循环访问任意数量的文件,请尝试以下代码。它的工作原理是因为 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