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

标签 excel vba macos

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

相关文章:

java - excel 中的日期格式与 apache poi

arrays - vba将公式复制到多个单元格

excel - 使用匹配的数字前缀添加新工作表

excel - 删除指示解锁单元格受 VBA 保护的错误

ms-access - rs.MoveFirst 是否隐含在 Access VBA 中?

c++ - top 如何查看内存使用情况

c++ - CMake 测试在 MacOS 上找不到库

python - 根据多列条件返回值

excel - 查找特定 PivotItem 的地址

bash - 为什么直接运行bash脚本不需要用户权限,但是运行脚本的.app文件需要用户权限?