2017-04-11 86 views
1

我期望做的是列出具有特定擴展名的目錄及其子目錄中的所有文件如.PDB使用VBA查詢目錄和目錄中的所有子文件夾,並返回特定文件擴展名的列A中的完整文件路徑

,並返回這些結果說A列中

下面的代碼工作,但我不確定語法的使用只返回一個特定的文件擴展名類型。

Sub ListFiles() 
Const sRoot  As String = "Y:\Engineering\Database Versions\Chillers" 
Dim t As Date 

Application.ScreenUpdating = False 
With Columns("A:C") 
    .ClearContents 
    .Rows(1).Value = Split("File,Size,Date", ",") 
End With 

t = Timer 
NoCursing sRoot 
Columns.AutoFit 
Application.ScreenUpdating = True 
End Sub 

Sub NoCursing(ByVal sPath As String) 
Const iAttr  As Long = vbNormal + vbReadOnly + _ 
     vbHidden + vbSystem + _ 
     vbDirectory 
Dim col   As Collection 
Dim iRow  As Long 
Dim jAttr  As Long 
Dim sFile  As String 
Dim sName  As String 

If Right(sPath, 1) <> "\" Then sPath = sPath & "\" 

Set col = New Collection 
col.Add sPath 

iRow = 1 

Do While col.count 
    sPath = col(1) 

    sFile = Dir(sPath, iAttr) 

    Do While Len(sFile) 
     sName = sPath & sFile 

     On Error Resume Next 
     jAttr = GetAttr(sName) 
     If Err.Number Then 
      Debug.Print sName 
      Err.Clear 

     Else 
      If jAttr And vbDirectory Then 
       If Right(sName, 1) <> "." Then col.Add sName & "\" 
      Else 
       iRow = iRow + 1 
       If (iRow And &H3FF) = 0 Then Debug.Print iRow 
       Rows(iRow).Range("A1:C1").Value = Array(sName, _ 
                 FileLen(sName), _ 
                 FileDateTime(sName)) 
      End If 
     End If 
     sFile = Dir() 
    Loop 
    col.Remove 1 
Loop 
End Sub 
+1

在Google和SO上有很多答案可用。 – ManishChristian

+0

你是正確的appologies。我添加了一個適用於我的用例的示例,但它缺少一個部分。 –

回答

1

與下面的代碼更改Else...End If一部分,它只能與.pdb擴展打印文件。

'Your existing code 
Else 
    If InStr(1, sName, ".pdb", vbTextCompare) > 0 Then 
     iRow = iRow + 1 
     If (iRow And &H3FF) = 0 Then Debug.Print iRow 
     Rows(iRow).Range("A1:C1").Value = Array(sName, _ 
               FileLen(sName), _ 
               FileDateTime(sName)) 
    End If 
End If 
'Your existing code 
+0

非常感謝! –

+0

很高興能夠幫助... :) – ManishChristian

+0

將下面的功能添加到此有多困難。要在日期之後添加另一個標題並將其標題爲包含文件夾,那麼只返回該文件所在文件夾的文件夾名稱,而不是完整路徑? –

相關問題