列出excel中包含链接的文件名

时间:2014-10-13 14:41:51

标签: excel excel-vba directory directory-structure vba

有没有办法在Excel工作表的不同目录中列出文件名和链接(这样可以点击文件名旁边的链接,文件会打开)?

  • 我准备写一个剧本,但我不知道任何特定的方法或命令。
  • 我不想输入整件事。
  • 我不关心目录/树结构,但文件链接应该存在。
  • 有一个目录包含许多其他文件夹,其中包含我需要列出的文件,主要是* .pdf' s。

任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码获取文件名和文件路径将主文件夹设置为strFolderPath

'Global Declaration for Start Row

Public lngRow As Long

Sub pReadAllFilesInDirectory()

    Dim strFolderPath               As String
    Dim BlnInclude_subfolder        As Boolean

    'Set Path here
    strFolderPath = "C:\"

    'set start row
    lngRow = 1

    'Set this true if you want list of sub-folders as well
    BlnInclude_subfolder = True

    '---------- Reading of files in folders and sub-folders------
    Call ListMyFiles(strFolderPath, BlnInclude_subfolder)
    '---------- Reading of files in folders and sub-folders------

End Sub

Sub ListMyFiles(mySourcePath As String, blnIncludeSubfolders As Boolean)

    Dim MyObject            As Object
    Dim mySource            As Object
    Dim mySubFolder         As Object
    Dim myfile              As Object
    Dim iCol                As Long

    Set MyObject = CreateObject("Scripting.FileSystemObject")
    Set mySource = MyObject.GetFolder(mySourcePath)

    'Loop in each file in Folder
    For Each myfile In mySource.Files

        iCol = 1
        Sheet1.Cells(lngRow, iCol).Value = myfile.Name  'File Name
        iCol = iCol + 1
        Sheet1.Cells(lngRow, iCol).Value = myfile.Path  'File Path/Location
        lngRow = lngRow + 1

    Next

    If blnIncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next
    End If

End Sub

答案 1 :(得分:0)

快速seach得出了我相信您正在寻找的答案。

Sub Example1()
Dim objFSO As Object 
Dim objFolder As Object 
Dim objFile As Object 
Dim i As Integer 

'Create an instance of the FileSystemObject 
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object 
Set objFolder = objFSO.GetFolder("D:\Stuff\Business\Temp")
i = 1
'loops through each file in the directory 
For Each objFile In objFolder.Files
    'select cell 
    Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select 
    'create hyperlink in selected cell 
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _ 
        objFile.Path, _ 
        TextToDisplay:=objFile.Name 
    i = i + 1 
Next objFile
End Sub