使用文件夹,Excel中的文件名填充单元格

我正在使用Excel 2010

我想插入具有特定文件夹位置的文件列表的文件名到Excel单元格中。

即如果文件path是:C:\ Users \ NAME \ Documents \ FolderPath

并在FolderPath中我有几个文件的某种types(File001.DAT … File00N.DAT)

我怎样才能填充文件名* .DAT的某个列(并在某一行开始)的所有单元格?

提前致谢。

更新:我使用命令提示符将文件名写入文本文件。 在命令提示符下,我导航到有问题的目录:

CD /目录/ /文件

然后我把这些文件写到一个文本文件中,如下所示:

dir / b * .png> FIles.txt

旗/ b只给我名字。 然后我复制了所有的名字并粘贴到Excel中。 这并不像布鲁斯·韦恩的解决scheme那么强大,但是现在它做了我所需要的。

只需通过标准输出stream检索DIR命令的输出即可。 比Dir$()快得多,不需要任何循环!

 Sub Foo() Dim strFolderName As String Dim strFileType As String Dim pasteRange As Range Dim returnVals As Variant '// set parameters, change as required strFolderName = "C:\Users\NAME\Documents\FolderPath\" strFileType = "*.DAT" Set pasteRange = Range("C5") '// retrieve output of DIR command from CMD.exe returnVals = Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & strFolderName & _ strFileType & """ /B /A:-D").StdOut.ReadAll, vbCrLf), ".") '// Display results in chosen column pasteRange.Resize(UBound(returnVals) + 1, 1).value = WorksheetFunction.Transpose(returnVals) End Sub 

一个简单而快速的方法是使用一个循环来检查目录中每个文件的扩展名:

 Sub t() Dim MyObj As Object, MySource As Object, file As Variant Dim i& file = Dir("C:\Users\me\Desktop\") i = 1 While (file <> "") Debug.Print Right(file, 3) If Right(file, 3) = "dat" Then Cells(i, 1).Value = "found " & file i = i + 1 End If file = Dir Wend End Sub 

只要根据需要调整Cells(i,1)

另一种方法 – 尽pipeEnumerateFiles函数基本上与BruceWaynes相同。

 Sub PopulateSheet() Dim lRow As Long Dim colFiles As Collection Dim vFile As Variant With ThisWorkbook.Worksheets("Sheet1") 'This will find the last row in column A, but 'can use a static number or any other method to return a row number. lRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1 Set colFiles = New Collection 'Remember to put the final \ in the file path. EnumerateFiles "C:\Users\NAME\Documents\FolderPath\", _ "*.DAT", colFiles For Each vFile In colFiles .Cells(lRow, 1) = Mid(vFile, InStrRev(vFile, "\") + 1) lRow = lRow + 1 Next vFile End With End Sub '//Places all file names with FileSpec extension into a collection. Sub EnumerateFiles(ByVal sDirectory As String, _ ByVal sFileSpec As String, _ ByRef cCollection As Collection) Dim sTemp As String sTemp = Dir$(sDirectory & sFileSpec) Do While Len(sTemp) > 0 cCollection.Add sDirectory & sTemp sTemp = Dir$ Loop End Sub