문제

I'm trying to place the names of all of the filenames in a folder into a list on excel, so that there is one filename per cell.

However, using the code below, it writes in the number of files in the folder -1. So, if there are 4 files in the folder, it only puts in three of them.

This is my first time using "Dir", and I can't spot what I'm doing wrong for the life of me!

Here's the code:

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
도움이 되었습니까?

해결책

It's replacing file on the first pass before you print it.

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

Here file(file = Dir) is just populated again at the end of the loop.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top