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

posted @ 2018-06-11 21:41  天上白玉京_32  阅读(7809)  评论(0编辑  收藏  举报