如何在vba中获取文件夹中文件的名称?

时间:2018-04-30 12:20:37

标签: vba excel-vba excel

我正在尝试在xlsm中插入图片,所以我需要代码来获取文件夹中的文件名(jpg文件),因为它们都是随机命名的

1 个答案:

答案 0 :(得分:1)

Dir,使用您的文件夹和通配符(例如FileName = Dir("D:\SomeFiles\New Folder\*"): MsgBox FileName)调用一次以获取文件夹中的第一个文件,并且在没有任何参数的情况下重复获取其余文件。 (例如While Len(FileName)>1: FileName = Dir(): MsgBox FileName: Wend)将以无特定顺序运行文件。

更高级的例子:

Option Explicit

Private Sub FileDemonstration(FolderName As String)
    Dim FileName As String, FileList() As String, lCount As Long
    lCount = 0
    FileName = Dir(FolderName & "\*")
    While Len(FileName) > 1
        lCount = lCount + 1
        ReDim Preserve FileList(1 To lCount)
        FileList(lCount) = FileName
        FileName = Dir()
    Wend
    'FileList is now an array with all of the files in the folder in it.
    'Do with it what you will
    If lCount < 1 Then
        Debug.Print "No Files Found"
    Else
        For lCount = LBound(FileList) To UBound(FileList)
            Debug.Print "File" & Format(lCount, "000") & ": " & FileList(lCount)
        Next lCount
    End If
End Sub