在本文中,我们将创建一个宏以列出文件夹中的所有文件。

ArrowMain

运行宏时,将从单元格A17开始显示文件名和文件路径。

ArrowOutput

逻辑解释

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

“ subfolder_files”宏将文件夹路径和布尔值作为输入,并返回文件夹内的文件名。

“ getting_filelist_in_folder”用于调用“ subfolder_files”宏。它为宏提供文件夹路径值,并将布尔值设置为“ true”。同样,当需要子文件夹内的文件名时,我们将布尔值设置为“ true”。

代码说明

folder_path = Sheet1.TextBox1.Value上面的代码用于从文本框中提取字符串值。

调用subfolder_files(folder_path,True)

上面的代码用于调用“ subfolder_files”宏。它分配文件夹路径,并将“ include_subfolder”属性设置为true。

设置fso = CreateObject(“ scripting.filesystemobject”)

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

设置subfolder1 = fso.getfolder(folder_path)

上面的代码用于创建已定义文件夹的对象。

对于每个folder1在subfolder1.subfolders中调用subfolder_files(folder1,True)

Next上面的代码用于浏览主文件夹中的所有子文件夹。

Dir(folderpath1&“ * .xlsx”)

上面的代码用于获取excel文件名。

而文件名<>“”

count1 = count1 +1 ReDim保留文件数组(1到count1)

filearray(count1)=文件名filename = Dir()

Wend上面的代码用于创建一个数组,其中包含文件夹中存在的所有文件名。

对于i = 1到UBound(filearray)

单元格(lastrow,1).Value = folderpath1&filearray(i)

lastrow = lastrow + 1 Next上面的代码用于将数组中的文件名分配给工作簿。

请遵循以下代码

Option Explicit

Sub subfolder_files(folderpath1 As Variant, Optional include_subfolder As Boolean)

'Checking whether to include subfolder or not

If include_subfolder Then



'Declaring variables

Dim filename, filearray() As String

Dim lastrow, count1, i As Integer



'Checking whether folder path contain backslash as last character

If Right(folderpath1, 1) <> "\" Then

folderpath1 = folderpath1 & "\"

End If



'Getting the filename of the first file in the defined folder path

filename = Dir(folderpath1 & "*.xlsx")



'Getting the row number of last cell

lastrow = ActiveCell.SpecialCells(xlCellTypeLastCell).Row + 1



count1 = 0



'Looping through all the files in the folder

While filename <> ""

count1 = count1 + 1

ReDim Preserve filearray(1 To count1)

filearray(count1) = filename

filename = Dir()

Wend



On Error GoTo last



'Adding file name to workbook

For i = 1 To UBound(filearray)

Cells(lastrow, 1).Value = folderpath1 & filearray(i)

lastrow = lastrow + 1

Next



End If

last:

End Sub

Sub getting_filelist_in_folder()

'Declaring variables

Dim folder_path As String

Dim fso As Object, folder1, subfolder1 As Object

'Getting path of the folder

folder_path = Sheet1.TextBox1.Value

'Checking whether folder path contain backslash as last character

If Right(folder_path, 1) <> "\" Then

folder_path = folder_path & "\"

End If

'Calling subfolder_files macro

Call subfolder_files(folder_path, True)

'Creating object of File system object

Set fso = CreateObject("scripting.filesystemobject")

Set subfolder1 = fso.getfolder(folder_path)

'Looping through each subfolder

For Each folder1 In subfolder1.subfolders

Call subfolder_files(folder1, True)

Next

End Sub

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

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