在本文中,我们将创建一个宏来收集文件夹中所有文件的详细信息。

在运行宏之前,我们需要在文本框中指定文件夹的路径。

ArrowMain

运行宏时,它将返回文件夹中所有文件的文件名,文件路径,文件大小,创建日期和最后修改日期。

ArrowOutput

逻辑解释

在本文中,我们创建了两个宏“ ListFilesInFolder”和“ TestListFilesInFolder”。

“ ListFilesInFolder”宏将显示与文件夹中所有文件有关的详细信息。

“ TestListFilesInFolder”宏用于指定标头并调用“ ListFilesInFolder”宏。

代码说明

设置FSO = CreateObject(“ Scripting.FileSystemObject”)

上面的代码用于创建文件系统对象的新对象。

设置SourceFolder = FSO.GetFolder(SourceFolderName)

上面的代码用于创建路径指定的文件夹的对象。

Cells(r,1).Formula = FileItem.Name Cells(r,2).Formula = FileItem.Path Cells(r,3).Formula = FileItem.Size Cells(r,4).Formula = FileItem.DateCreated Cells( r,5).Formula = FileItem.DateLastModified上面的代码用于提取文件的详细信息。

对于SourceFolder.SubFolders中的每个子文件夹’为子文件夹ListFilesInFolder SubFolder.Path,True Next SubFolder调用相同的过程上面的代码用于提取子文件夹中所有文件的详细信息。

Columns(“ A:E”)。Select Selection.ClearContents上面的代码用于将内容从列A删除到E。

请遵循以下代码

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

Option Explicit

Sub ListFilesInFolder(ByVal SourceFolderName As String, ByVal IncludeSubfolders As Boolean)

'Declaring variables

Dim FSO As Object

Dim SourceFolder As Object

Dim SubFolder As Object

Dim FileItem As Object

Dim r As Long



'Creating object of FileSystemObject

Set FSO = CreateObject("Scripting.FileSystemObject")

Set SourceFolder = FSO.GetFolder(SourceFolderName)

r = Range("A65536").End(xlUp).Row + 1

For Each FileItem In SourceFolder.Files

'Display file properties

Cells(r, 1).Formula = FileItem.Name

Cells(r, 2).Formula = FileItem.Path

Cells(r, 3).Formula = FileItem.Size

Cells(r, 4).Formula = FileItem.DateCreated

Cells(r, 5).Formula = FileItem.DateLastModified



r = r + 1



Next FileItem

'Getting files in sub folders

If IncludeSubfolders Then

For Each SubFolder In SourceFolder.SubFolders

'Calling same procedure for sub folders

ListFilesInFolder SubFolder.Path, True

Next SubFolder

End If

Set FileItem = Nothing

Set SourceFolder = Nothing

Set FSO = Nothing

ActiveWorkbook.Saved = True

End Sub

Sub TestListFilesInFolder()

'Declaring variable

Dim FolderPath As String

'Disabling screen updates

Application.ScreenUpdating = False

'Getting the folder path from text box

FolderPath = Sheet1.TextBox1.Value

ActiveSheet.Activate

'Clearing the content from columns A:E

Columns("A:E").Select

Selection.ClearContents

'Adding headers

Range("A14").Formula = "File Name:"

Range("B14").Formula = "Path:"

Range("C14").Formula = "File Size:"

Range("D14").Formula = "Date Created:"

Range("E14").Formula = "Date Last Modified:"

'Formating of the headers

Range("A14:E14").Font.Bold = True

'Calling ListFilesInFolder macro

ListFilesInFolder FolderPath, True

'Auto adjusting the size of the columns

Columns("A:E").Select

Selection.Columns.AutoFit

Range("A1").Select

End Sub

我们很希望收到您的来信,请让我们知道我们如何才能改善我们的工作并使您的工作更好。写信给我们[email protected]