【发布时间】:2017-12-26 07:52:26
【问题描述】:
我想通过 Excel VBA 获取 子文件夹 名称和文件名。
我真正想要的是Column A 显示子文件夹名称,Column B 显示文件名。
这是我的代码:
Option Explicit
Private xRow As Long
Sub Get_MAIN_File_Names()
Dim fso As FileSystemObject
Dim xDirect As String
Dim xRootFolder As Folder
Dim DrawingNumb As String
Dim RevNumb As String
Dim rootFolderStr As String
Set fso = New FileSystemObject
xRow = 0
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Main File"
.Show
'PROCESS ROOT FOLDER
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
Set xRootFolder = fso.GetFolder(xDirect)
ProcessFolder fso, xRootFolder
End If
End With
End Sub
Private Sub ProcessFolder(fso As FileSystemObject, xFolder As Folder)
Dim xFiles As Files
Dim xFile As File
Dim xSubFolders As Folders
Dim xSubFolder As Folder
Dim xSubFolderName As String
Dim xFileName As String
Dim xFileTime As String
Set xFiles = xFolder.Files
'Adding Column names
Cells(1, "A").Value = "SubFolder Name"
Cells(1, "B").Value = "File Name"
Cells(1, "C").Value = "Modified Date/Time"
For Each xSubFolder In xSubFolders
xSubFolderName = xSubFolder.Name
ActiveCell.Offset(xRow, 0) = xSubFolderName
xRow = xRow + 1
Next xSubFolder
'LOOPS THROUGH EACH FILE NAME IN FOLDER
For Each xFile In xFiles
'EXTRACT INFORMATION FROM FILE NAME
xFileName = xFile.Name
xFileTime = xFile.DateLastModified
'INSERT INFO INTO EXCEL
ActiveCell.Offset(xRow, 1) = xFileName
ActiveCell.Offset(xRow, 2) = xFileTime
xRow = xRow + 1
Next xFile
Set xSubFolders = xFolder.SubFolders
For Each xSubFolder In xSubFolders
ProcessFolder fso, xSubFolder
Next xSubFolder
End Sub
但是,我没有得到我想要的。我认为问题出在这里:
For Each xSubFolder In xSubFolders
xSubFolderName = xSubFolder.Name
ActiveCell.Offset(xRow, 0) = xSubFolderName
xRow = xRow + 1
Next xSubFolder
我忽略了哪一部分?或者有没有别的办法解决?
我认为代码太长了。也许效率低下。如何修改代码?
【问题讨论】:
-
我认为如果你删除你认为有问题的整个部分,而是在你写出其他信息的部分中添加一行
ActiveCell.Offset(xRow, 0) = xFolder.Name,它可能会起作用。 -
参考this
-
@YowE3K 太好了。有用。我想你可以回答这个问题,我会标记它。