2014-04-25 42 views
0

我使用以下代码将文件名读入Excel工作表,但我想包括子文件夹并捕获整个文件路径。我尝试了一些东西,但都没有工作。我已经从编辑其他人的代码碎片拼凑起来,在我的情况下运行,不幸的是这意味着我的理解不够彻底。从文件夹和子文件夹读取文件路径到Excel中

的文件是音频文件(WAV或MP3),电子表格的其余部分将包含将被用于标记文件的元数据:艺术家,标题,专辑等

Option Explicit 
Sub GetFileNames() 
Dim xRow As Long 
Dim xDirect$, xFname$, InitialFoldr$ 
InitialFoldr$ = "C:\" 

With Application.FileDialog(msoFileDialogFolderPicker) 
.InitialFileName = Application.DefaultFilePath & "\" 
.Title = "Please select the folder to list audio files from" 
.InitialFileName = InitialFoldr$ 
.Show 

    If .SelectedItems.Count <> 0 Then 
    xDirect$ = .SelectedItems(1) & "\" 
    xFname$ = Dir(xDirect$, 7) 
    Do While xFname$ <> "" 
    Worksheets("Metadata").Activate 
    ActiveSheet.Range("A2").Select 
    ActiveCell.Offset(xRow) = xFname$ 
    xRow = xRow + 1 
    xFname$ = Dir 
    Loop 

    Dim x& 
    With Application 
      .ScreenUpdating = False 
      Rows.Hidden = False 
      Rows.Hidden = True 
     For x = 1 To Rows.Count 
      If .WorksheetFunction.CountA(Rows(x)) > 0 Then Rows(x).Hidden = False 
     Next x 
     .ScreenUpdating = False 
    End With 

    Worksheets("Metadata").Visible = True 
    Worksheets("Menu").Visible = False 

End If 
End With 
End Sub 

我很新的VBA,但我开始抓住它的一部分。

回答

0

此代码将从文件夹及其所有子文件夹中提取所有mp3。祝你好运与VBA!

Public Sub FindFiles() 
'you must add a reference to 'Microsoft Shell Controls And Automation' 

Dim shl As Shell32.Shell 
Dim fol As Shell32.Folder 
Dim row As Long 

Set shl = New Shell32.Shell 
Set fol = shl.Namespace("E:\CDs\") 
row = 1 

ProcessFolderRecursively fol, row 

End Sub 

Private Sub ProcessFolderRecursively(fol As Shell32.Folder, ByRef row As Long) 

Dim item As Shell32.FolderItem 
Dim fol2 As Shell32.Folder 

If Not fol Is Nothing Then 
    For Each item In fol.Items 
     If item.IsFolder Then 
      Set fol2 = item.GetFolder 
      ProcessFolderRecursively fol2, row 
     Else 
      'you might need to edit the criterion here 
      If item.Type = "MP3 Format Sound" Then 
       Cells(row, 1) = item.Path 
       row = row + 1 
      End If 
     End If 
    Next 
End If 

End Sub 
+0

谢谢,但我不希望它只是找到的MP3,它需要证明我的文件夹中的一切,它可能是MP3音乐,wav文件,aiffs,WMA格式等等等等混合它完美的是对于根文件夹和文件名,我只希望通过查看子文件夹和返回文件路径而不是名称来使它更加灵活。如果我发现我只需要文件名,我总是可以修剪路径。 – user3506327

+0

只要删除'如果item.Type = ...'行和相应的结束如果它下面,它会提取所有子文件夹中的所有文件 – steveo40

+0

如果这回答你的问题,那么你可以请标记为答案。谢谢 – steveo40

相关问题