【问题标题】:Why is this use of the "Dir" function not working as I intended?为什么“Dir”功能的这种使用没有按我的预期工作?
【发布时间】:2014-04-01 13:22:55
【问题描述】:

我正在尝试将文件夹中所有文件名的名称放入 Excel 列表中,以便每个单元格有一个文件名。

但是,使用下面的代码,它会写入文件夹 -1 中的文件数。因此,如果文件夹中有 4 个文件,则只放入其中的 3 个。

这是我第一次使用“Dir”,我一辈子都找不到自己做错了什么!

代码如下:

Sub PrintFilesNames()

Dim PathToFolder As String
Dim file As String
Dim cellOutput As String

Dim i As Integer

i = 6

PathToFolder = ThisWorkbook.Sheets("PDP Comparison").Cells(5, 2).Text
file = Dir(PathToFolder)

While (Len(file) > 0)
    file = Dir
    cellOutput = PathToFolder + file
    ThisWorkbook.Sheets("PDP Comparison").Cells(i, 2).Value = cellOutput
    Debug.Print (file)
    i = i + 1
Wend


End Sub

【问题讨论】:

    标签: excel vba dir


    【解决方案1】:

    它会在您打印之前的第一遍替换文件。

    file = Dir(PathToFolder)
    
    While (Len(file) > 0)    
        cellOutput = PathToFolder + file
        ThisWorkbook.Sheets("PDP Comparison").Cells(i, 2).Value = cellOutput
        Debug.Print (file)
        i = i + 1
        file = Dir
    Wend
    

    这里的文件(file = Dir)只是在循环结束时再次填充。

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      相关资源
      最近更新 更多