【问题标题】:DIR function in vba works diffrent when passing a value directly and by a variable直接和通过变量传递值时,vba 中的 DIR 函数的工作方式不同
【发布时间】:2013-05-21 09:09:19
【问题描述】:

您好,当我使用*以下**代码时,我在系统的特定文件夹中有一些文件,它提供了该文件夹中的所有文件(直接传递路径)

filenm = Dir("C:\Documents and Settings\murugan.k\Desktop\Daily report automation\Eve report\trial\")

Do Until filenm = ""
ActiveSheet.Cells(ctr, 12).Value = filenm
ctr = ctr + 1
filenm = Dir()
Loop

但是当我将相同的路径存储在变量中并将变量传递给 dir 函数时,它只给了我两个文件(AUTOEXEC.BAT 和 bar.emf)

filenm = Dir(pth)
Do Until filenm = ""
ActiveSheet.Cells(ctr, 12).Value = filenm
ctr = ctr + 1
filenm = Dir()
Loop

有人可以帮我解决这个问题吗,因为我无法在宏中硬编码必须是动态的路径(根据用户进行更改)

【问题讨论】:

    标签: excel vba directory


    【解决方案1】:

    Dir() function 尝试不同的属性。

    path = "C:\Documents and Settings\murugan.k\Desktop\" & _ 
            "Daily report automation\Eve report\trial\"
    
    filenm = Dir(path, vbNormal)
    
    Do Until filenm = ""
        ActiveSheet.Cells(ctr, 12).Value = filenm
        ctr = ctr + 1
        filenm = Dir()
    Loop
    

    【讨论】:

    • 这也给了我同样的输出 AUTOEXEC.BAT & bar.emf
    • @murugan_kotheesan 您可以实际检查路径中指定的文件夹的内容吗?它有哪些文件?您是否尝试过使用cmd 导航到文件夹并显示文件?
    • 您的版本和@mehow 都按预期工作。两者都从目录中提取文件列表,无论是直接字符串还是strPathvariable。您确定该目录中的文件不止两个吗?
    • @mehow 是的,我检查了文件夹,它包含 5 个 csv 文件和 2 个 .xlx 文件
    【解决方案2】:

    我知道他是怎么弄对的

    b4 我的路径末尾没有“\”,所以我将路径与“\”连接起来,并将其放在另一个变量中,然后我将该变量传递给 DIR 函数(这不起作用)但现在我添加了“\”在输入本身的文件夹路径末尾,我将该变量传递给 DIR,它现在可以工作了

    '            checking the available files
    filenm = Dir(File_pth)
    Do Until filenm = ""
    ActiveSheet.Cells(ctr, 12).Value = filenm
    ctr = ctr + 1
    filenm = Dir()
    Loop
    

    【讨论】:

      【解决方案3】:

      好吧,对我来说,你的回答没有奏效,经过一番环顾后,我发现了一个小错误。您的代码一般都很好,但是“=”符号不起作用,因为

      当没有更多文件名匹配时,Dir 返回一个长度为零的字符串 ("")。

      至少我认为这是它对我的输出没有显示任何内容的原因。所以我会说它的工作原理是:

      Sub LoopThruDirectory2()
      
      Dim strPath As String
      Dim strFile As String
      Dim x As Integer
      strPath = ThisWorkbook.path
      strFile = Dir(strPath & "\")
      Do While strFile <> ""
          x = x + 1
          Debug.Print strFile
          strFile = Dir    ' Get next entry.
      Loop
      
      End Sub
      

      随意将“thisworkbook.path”设置为您的路径并根据需要处理 strFile。 (例如,见上文)。对于我的项目,用户想要选择一个选定的文件夹,所以我不得不使用“msoFileDialogFolderPicker”。以防万一有人遇到同样的问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        相关资源
        最近更新 更多