Determine .sheets.count on a Closed Excel Workbook

Hey Everybody!

I have a quick question that I've been wrecking my brain on...

I'm using VBA inside of Excel, and I'm trying to determine .sheets.count on a closed Excel Workbook.  

In a nutshell, here's the functionality that I need...

I have about 1000 folders that I need to loop through, then identify the .xls file inside of the folder and compare the number of sheets to the number of files in the folder.  Each folder will have 5-100 different files inside of it... With all of this in mind, I don't want to open each .xls file that I come across just to find .sheets.count and then close the .xls file.  Looping through each folder, then looping through each file, then opening the xls... In the end this takes about 7 hours to run this report.  I can have my team manually do this task faster.

I've already tried everything that I can think of to try and determine .sheets.count on a closed workbook, but nothing has worked just yet.

Please let me know if anyone has any suggestions.  At this point in time, I'm not even sure if it's possible to determine .sheets.count on a closed workbook.

Thanks in advanced!
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Richie_SimonettiIT OperationsCommented:
is there a posibility to store that the dat is stored ina cell of each workbook (i.e.: range A1 of Sheet1)?
If so, i have code to read data from closed workbook but stored in a cell, not a property like .count.
Not possible. Cant get properties of a worksheet without opening the workbook.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hey ! Zihif,

Try this code

It loops through the defined directory and subdirectory looking for xls files once found opens them setting the visible property to false and obtains the sheet count, closes the file looks at the next file. on my old celeron it took 25 seconds to get the info on 174 files and my system configuration is nothing to brag about.

it inserts the file path and name into columnA and sheet count on columnB and in C1 it sets up a counter showing the no of files found (can be disabled to further speeding it up). path is set to c:\temp\ change it accordingly.

(open a new workbook hit ALT+F11 and paste the code below, close the vbe window, in excel hit ALT+F8 select rSearch and click Run)

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" _
(ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" _
(ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias _
"GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Const MAX_PATH = 260
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Dim xlApp As Excel.Application
Dim wkb As Workbook
Function StripNulls(OriginalStr As String) As String
If (InStr(OriginalStr, Chr(0)) > 0) Then
OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
End If
StripNulls = OriginalStr
End Function
Function FindFilesAPI(path As String, SearchStr As String, _
FileCount As Integer, DirCount As Integer)
Dim FileName As String
Dim DirName As String
Dim dirNames() As String
Dim nDir As Integer
Dim i As Integer
Dim hSearch As Long
Dim Cont As Integer
If Right(path, 1) <> "\" Then path = path & "\"
nDir = 0
ReDim dirNames(nDir)
Cont = True
hSearch = FindFirstFile(path & "*", WFD)
Do While Cont
DirName = StripNulls(WFD.cFileName)
If (DirName <> ".") And (DirName <> "..") Then
If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
dirNames(nDir) = DirName
DirCount = DirCount + 1
nDir = nDir + 1
ReDim Preserve dirNames(nDir)
End If
End If
Cont = FindNextFile(hSearch, WFD)
Cont = FindClose(hSearch)
End If
hSearch = FindFirstFile(path & SearchStr, WFD)
Cont = True
While Cont
FileName = StripNulls(WFD.cFileName)
If (FileName <> ".") And (FileName <> "..") Then
FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
Set wkb = xlApp.Workbooks.Open(path & FileName)
shCnt = wkb.Sheets.Count
FileCount = FileCount + 1
ActiveSheet.Cells(1, 3).Value = FileCount
ActiveSheet.Cells(FileCount, 1).Value = path & FileName
ActiveSheet.Cells(FileCount, 2) = shCnt
End If
Cont = FindNextFile(hSearch, WFD) ' Get next file
Cont = FindClose(hSearch)
End If
If nDir > 0 Then
For i = 0 To nDir - 1
FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(i) _
& "\", SearchStr, FileCount, DirCount)
Next i
End If
End Function
Sub rSearch()
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Dim SearchPath As String, FindStr As String
Dim FileSize As Long
Dim NumFiles As Integer, NumDirs As Integer
FileSize = FindFilesAPI("c:\temp\", "*.xls", NumFiles, NumDirs)
Set wkb = Nothing
Set xlApp = Nothing
End Sub
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

(open a new workbook hit ALT+F11 and paste the code below, close the vbe window, in excel hit ALT+F8 select rSearch and click Run)

in my previous post the above line should be (just in case you are new to vba)

(open a new workbook hit ALT+F11 select insert-module menu and paste the code below, close the vbe window, in excel hit ALT+F8 select  rSearch  and click Run)
check this link, not the solution but some insights on getting info from a closed workbook. hope this helps,_Workbook,_and_Worksheets_in_VBA/Read_information_from_a_closed_workbook_using_VBA_in_Microsoft_Excel/473.html
Richie_SimonettiIT OperationsCommented:
Zihif, some feedback would be nice.
In the meantime, check this code:
' this code is from a site no longer available

Option Explicit

Sub ReadDataFromNewstock()
Dim FolderName As String, wbName As String, strRangeA As String, strRangeB
As String, strRangeC As String
Dim cValue1 As Variant, cValue2 As Variant, cValue3 As Variant
Dim objSheetCboBox As Object
Dim i As Long
Dim intFila As Integer
Set objSheetCboBox = Worksheets("Hoja1").ComboBox1

'objSheetCboBox.ComboBox1.Text = ""

With Application
.ScreenUpdating = False

FolderName = "C:\mis documentos\"
wbName = "newstock.xls"

    For i = 2 To 1500
        strRangeA = Chr(65) & i
        strRangeB = Chr(66) & i
        strRangeC = Chr(67) & i
        cValue1 = GetInfoFromClosedFile(FolderName, wbName, "stock",
        cValue2 = GetInfoFromClosedFile(FolderName, wbName, "stock",
        cValue3 = GetInfoFromClosedFile(FolderName, wbName, "stock",
        If InStr(1, cValue1, "/") Then
            With objSheetCboBox
                .AddItem cValue1
                .List(intFila, 1) = cValue2
                .List(intFila, 2) = cValue3
                intFila = intFila + 1
            End With
            .StatusBar = "Obteniendo Mercaderia de la marca: " & cValue2
            Exit For
        End If
    Next i
.ScreenUpdating = True
.StatusBar = False

End With
End Sub
Private Function GetInfoFromClosedFile(ByVal wbPath As String, wbName As
String, wsName As String, cellRef As String) As Variant
Dim arg As String
GetInfoFromClosedFile = ""
    arg = "'" & wbPath & "[" & wbName & "]" & wsName & "'!" &
Range(cellRef).Address(True, True, xlR1C1)
    On Error Resume Next
    GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function

ZihifAuthor Commented:
Hey guys-

My apologies for not responding sooner, however this was a work project and I took this weekend off :)

Unfortunately, I think that JDSHAW answered the question.  It appears that the modules from above are either pulling data from a cell, or still opening the actual workbooks.  Unforunately neither of which are resolving the reporting time frame issues.  I've tested both of them out, and they do work... However, they are still just as slow as my first module.  I think that the issue revolves around the fact that the directories that I'm pulling information from are on servers located on the East Coast.  Where as, I'm located on the West Coast.

Any suggestions on getting around an issue like this would be greatly appreciated.  I'm working with our data migration team to get this information closer to us, however that might be long in coming.  I'll keep this thread open for one more day, then award points to JDSHAW.

Thanks again for all of the great responses!
Could you write a service to copy the files locally at night or something and then run the open each file exe?

Richie_SimonettiIT OperationsCommented:
As you wish. Good luck.
ZihifAuthor Commented:

That's most likely the option that we will go with, however first I need our Admins to allocate more space on one of my team's shared drives.

Good luck!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.