2014-04-25 43 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

相關問題