【问题标题】:Excel: Search for all zip files inside a folderExcel:搜索文件夹内的所有 zip 文件
【发布时间】:2015-09-11 12:34:20
【问题描述】:

我有一个宏 (Loop through files in a folder using VBA?) 可以在文件夹中查找 zip 文件,但问题是最后一个 zip 文件的名称为空字符串。我怎样才能避免这个错误。

宏的代码:

Sub LoopThroughFiles()
    ' Define variables
    Dim file As String, folder As String

    ' Define working directory
    folder = "C:\Users\cportocarrero\Desktop\Curvas\"

    ' Define type of file to search for
    file = Dir(folder & "*.zip")

    ' Loop through all the files
    Do While Len(file) > 0
        Debug.Print file
        file = Dir
        MsgBox file
    Loop
End Sub

【问题讨论】:

  • 您的问题是您正在调试。打印file 的一个值,但是您在发送到 MsgBox 之前更改了file 变量。 KekuSemau 的回答显示了您的循环应该如何构建。您的While 测试不需要更改,因为Len(file) > 0 将具有与file <> "" 相同的效果

标签: excel vba


【解决方案1】:

你必须保持这样的循环:
- 在循环之前首先调用dir,然后
- while 循环
- 调用dir 应该是循环内的最后一个命令

file = Dir(folder & "*.zip")
Do While file <> ""
    Debug.Print file
    MsgBox file
    file = Dir
Loop

dir 返回一个空字符串时,这意味着没有更多的匹配项。

【讨论】:

  • +1 我在这里很挑剔,但是对 Dir 的调用 应该 是循环内的最后一个命令,但没有 i> 成为。它只需要毕竟使用了file 变量。
  • 是的,你完全正确。 +1 挑剔,我已经编辑了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
相关资源
最近更新 更多