【问题标题】:VBA - Loop through folder with blank spaces addressVBA - 循环浏览带有空格地址的文件夹
【发布时间】:2016-07-20 02:25:17
【问题描述】:

我有一个功能要求用户选择一个文件夹,然后选择另一个应该输出该文件夹中所有文件名的功能。 我一直在尝试以下但它不起作用,因为文件夹地址包含空格。你能帮忙吗?

'gets folder address
recsFolder = Functions.GetFolder("C:\")

'Loop through files in folder
Dim StrFile As String
StrFile = Dir(recsFolder)
Do While Len(StrFile) > 0
    Debug.Print StrFile
    StrFile = Dir
Loop

谢谢!

编辑: GetFolder 的代码

Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
    NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

空格是指地址中存在的空格(即在每日和摘要之间) C:\Users\User1\Desktop\每日总结

【问题讨论】:

  • GetFolder 函数的代码是什么?什么是“空格”?
  • @MacroMan 请查看编辑后的帖子

标签: vba directory


【解决方案1】:

您需要向Dir() 提供文件模式才能列出文件。

改为:

StrFile = Dir$(recsFolder & "\*.*")

【讨论】:

  • 干杯,它也确实有效。 Dir 后面的 $ 的作用是什么?
  • @peetman 作为后续,该链接上接受的答案很有用 - 但实际上并不是使用 $ 的原因。下面的几个答案解释了原因:stackoverflow.com/a/3389455/4240221
  • @MacroMan 谢谢你的解释。它返回一个字符串。
  • 伙计们,我遇到了另一个问题。当循环在某个时刻运行时,Dir 获取值 。我怎样才能避免这种情况?
【解决方案2】:

改变

StrFile = Dir(recsFolder)

StrFile = Dir(recsFolder & "\*.*")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多