您的位置:首页 > 编程语言 > VB

Excel vba获取文件夹内文件名

2020-02-17 08:32 295 查看

来源: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

转载于:https://www.cnblogs.com/panli-32/p/9169408.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
a819281 发布了0 篇原创文章 · 获赞 0 · 访问量 492 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: