2016-12-22 56 views
0

我有下面的代碼返回一個文件夾中的文件數量。獲得從表文件夾路徑在Excel VBA來計算該文件夾內的文件

Sub sample() 

    Dim FolderPath As String, path As String, count As Integer 
    FolderPath = "C:\Documents and Settings\Santosh\Desktop" 

    path = FolderPath & "\*.xls" 

    Filename = Dir(path) 

    Do While Filename <> "" 
     count = count + 1 
     Filename = Dir() 
    Loop 

    Range("Q8").Value = count 
    'MsgBox count & " : files found in folder" 
End Sub 

我需要參數化FolderPath如excel工作表本身的輸入,使得我輸入單元格A1中的文件夾路徑,並獲得沒有文件的B1。我對Excel宏很新 - 如果這是非常基本的原因吧。我怎樣才能做到這一點?

回答

1

您可以通過以下方式從單元格A1發送FOLDERPATH字符串:

Sub sample() 

    Dim FolderPath As String, path As String, count As Integer 
    FolderPath = Range("A1") 

    path = FolderPath & "\*.xls" 

    Filename = Dir(path) 

    Do While Filename <> "" 
     count = count + 1 
     Filename = Dir() 
    Loop 

    Range("B1").Value = count 
    MsgBox count & " : files found in folder" 

End Sub 

要在單元格A1您的文件夾路徑和運行宏。

你會得到B1細胞計數

編輯

上循環的填充柱A1,A2,A3的所有文件夾路徑......並在相應的單元格是B1,B2獲得數,B3 ......繼續象下面這樣:

獲取在哪個文件夾路徑已經充滿

TotalRows = Range("A" & Rows.count).End(xlUp).Row 

然後總行從1循環到第A列填充行。

Sub sample() 

    Dim FolderPath As String, path As String, count As Integer 
    Dim TotalRows As Integer 

    TotalRows = Range("A" & Rows.count).End(xlUp).Row 

    For i = 1 To TotalRows 
    count = 0 
    FolderPath = Range("A" & i) 

    path = FolderPath & "\*.xls" 

    Filename = Dir(path) 

    Do While Filename <> "" 
     count = count + 1 
     Filename = Dir() 
    Loop 

    Range("B" & i).Value = count 
    'MsgBox count & " : files found in folder" 

    Next i 
End Sub 
+0

謝謝噸 - 這工作。如果我需要在A列中填寫多個文件夾路徑並一次性獲取B列中相應的文件數量?我在哪裏改變它? –

+0

請參閱A中的多個文件夾路徑的編輯答案,並在B列中計數。@SriramIlango –

0

考慮您的宏做工精細,所有你需要做的是你的Sub轉換成Function這樣:

Function FileCounter(FolderPath as String) 

    Dim path As String, count As Integer 

    path = FolderPath & "\*.xls" 

    Filename = Dir(path) 

    Do While Filename <> "" 
     count = count + 1 
     Filename = Dir() 
    Loop 

    FileCounter = count 

End Function 

接下來,在Excel中做的需要和類型A1文件夾路徑和B1 =FileCounter(A1)

請注意,你得到的文件數只.xls擴展,但不.xlsx.xlsm等。要在結果中包含所有Excel文件,您需要將擴展​​模板更改爲\*.xls*

+0

謝謝 - 工作就像一個魅力:) –

相關問題