【问题标题】:Loop though files in a Folder on Mac OS X - VBA Excel 2011在 Mac OS X 上循环浏览文件夹中的文件 - VBA Excel 2011
【发布时间】:2011-09-03 17:54:03
【问题描述】:

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

【问题讨论】:

标签: excel vba macos


【解决方案1】:

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

【讨论】:

  • 通配符 (*) 不能像这样在 Mac 上工作。见上面 Siddharth 给出的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
相关资源
最近更新 更多