Excel vba獲取文件夾內文件名


來源:http://www.360doc.com/content/13/1225/16/1086327_340041443.shtml

 

Sub test()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long

'顯示打開文件夾對話框
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub '未選擇文件夾
strFolder = .SelectedItems(1)
End With
'獲取文件夾中的所有文件列表
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "未找到文件", vbInformation
Exit Sub
End If

For x = 0 To UBound(varFileList)
Cells(x + 1, 1) = varFileList(x)
Next x

End Sub

Private Function fcnGetFileList(ByVal strPath As String, Optional strFilter As
String) As Variant


' 將文件列表放到數組
Dim f As String
Dim i As Integer
Dim FileList() As String


If strFilter = "" Then strFilter = "*.*"
Select Case Right(strPath, 1)
Case "\", "/"
strPath = Left(strPath, Len(strPath) - 1)
End Select

ReDim Preserve FileList(0)
f = Dir(strPath & "\" & strFilter)
Do While Len(f) > 0
ReDim Preserve FileList(i) As String
FileList(i) = f
i = i + 1
f = Dir()
Loop
If FileList(0) <> Empty Then
fcnGetFileList = FileList
Else
fcnGetFileList = False
End If
End Function


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM