Question : Count Worksheet Tabs on Excel File

Experts,
Is it possible to count all the Worksheet tabs on and Excel file without opening it up and doing it manually?  I need do this on a number of Excel files.  Looking for ideas.  

Thanks,
Bob

Answer : Count Worksheet Tabs on Excel File

Small correction
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
Option Explicit
 
 
 
Public Function fGetFiles(ByVal strSpec As String, ByVal strPath As String) As String()
    Dim strFile() As String, strTemp As String
    Dim lngCount As Long, lngNum As Long
    Const Chunk = 200
    
    On Error GoTo errGetFiles
    lngNum = Chunk
    ReDim strFile(1 To lngNum)
    If Right$(strPath, 1) <> "\" Then strPath = strPath & "\"
    lngCount = 1
    strTemp = Dir(strPath & strSpec)
    Do While Len(strTemp) > 0
        If lngCount > UBound(strFile) Then
            lngNum = lngNum + Chunk
            ReDim Preserve strFile(1 To lngNum)
        End If
        strFile(lngCount) = strTemp
        strTemp = Dir
        lngCount = lngCount + 1
    Loop
    If lngCount > 1 Then
        ReDim Preserve strFile(1 To lngCount - 1)
    Else
        ReDim strFile(-1 To -1)   'Avoid errors when no files.  Send back a one element blank array.
    End If
    fGetFiles = strFile
    Exit Function
errGetFiles:
    
    MsgBox Err.Description, vbCritical, "fGetFiles"
 
End Function
 
Private Function CountWorksheets(Filename As String) As Integer
    Dim xlApp As Object
   Dim xlWrk As Object
   Set xlApp = CreateObject("EXCEL.APPLICATION")
   Set xlWrk = xlApp.Workbooks.Open(Filename)
   CountWorksheets = xlApp.ActiveWorkbook.Worksheets.Count
   xlWrk.Close
   xlApp.Quit
   Set xlWrk = Nothing
   Set xlApp = Nothing
   
 
End Function
 
 
Private Sub CommandButton1_Click()
    Dim strFiles() As String
    Dim i As Integer
    Dim strPath As String
    strPath = txtPath.Text
    
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
    If Len(Dir(strPath)) = 0 Then
        MsgBox "Please enter a valid path"
        Exit Sub
    End If
    
    strFiles = fGetFiles("*.xls", strPath)
    For i = 1 To UBound(strFiles)
        
        ActiveSheet.Cells(i, 1).Value = strFiles(i)
        ActiveSheet.Cells(i, 2).Value = CountWorksheets(strPath & strFiles(i))
        
    Next
End Sub
Random Solutions  
 
programming4us programming4us