什么意思呢?
比如說(shuō),A文件下有B文件夾,B文件夾下有C文件夾,C文件夾下又有D文件夾……
也就是傳說(shuō)中的子又生孫,孫又生子;子又有子,子又有孫;子子孫孫無(wú)窮匱也……
……想什么呢 這是赤果果的愚公移山……
此時(shí)如何提取每個(gè)文件夾下的文件名呢?
代碼如下:
(友情提示,代碼看不全可以拖動(dòng))
Sub AutoAddLink()
Dim strFldPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
'用戶(hù)選擇指定文件夾
.Title = '請選擇指定文件夾。'
If .Show Then strFldPath = .SelectedItems(1) Else Exit Sub
'未選擇文件夾則退出程序,否則將地址賦予變量strFldPath
End With
Application.ScreenUpdating = False
'關(guān)閉屏幕刷新
Range('a:b').ClearContents
Range('a1:b1') = Array('文件夾', '文件名')
Call SearchFileToHyperlinks(strFldPath)
'調取自定義函數SearchFileToHyperlinks
Range('a:b').EntireColumn.AutoFit
'自動(dòng)列寬
Application.ScreenUpdating = True
'重開(kāi)屏幕刷新
End Sub
Function SearchFileToHyperlinks(ByVal strFldPath As String) As String
Dim objFld As Object
Dim objFile As Object
Dim objSubFld As Object
Dim strFilePath As String
Dim lngLastRow As Long
Dim intNum As Integer
Set objFld = CreateObject('Scripting.FileSystemObject').GetFolder(strFldPath)
'創(chuàng )建FileSystemObject對象引用
For Each objFile In objFld.Files
'遍歷文件夾內的文件
lngLastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
strFilePath = objFile.Path
intNum = InStrRev(strFilePath, '\')
'使用instrrev函數獲取最后文件夾名截至的位置
Cells(lngLastRow, 1) = Left(strFilePath, intNum - 1)
'文件夾地址
Cells(lngLastRow, 2) = Mid(strFilePath, intNum + 1)
'文件名
ActiveSheet.Hyperlinks.Add Anchor:=Cells(lngLastRow, 2), _
Address:=strFilePath, ScreenTip:=strFilePath
'添加超鏈接
Next objFile
For Each objSubFld In objFld.SubFolders
'遍歷文件夾內的子文件夾
Call SearchFileToHyperlinks(objSubFld.Path)
Next objSubFld
Set objFld = Nothing
Set objFile = Nothing
Set objSubFld = Nothing
End Function
代碼使用了FileSystemObject對象和遞歸的方法實(shí)現文件夾和文件的遍歷功能。分別將文件夾名稱(chēng)和文件名提取在表格的A/B列,并對文件名創(chuàng )建了超鏈接,示例結果如下圖所示。
聯(lián)系客服