Determine .sheets.count on a Closed Excel Workbook

Posted on 2003-10-31
Medium Priority
Last Modified: 2011-10-03

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!
Question by:Zihif
  • 3
  • 3
  • 2
  • +2
LVL 16

Expert Comment

ID: 9660639
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.

Accepted Solution

JDSHAW earned 400 total points
ID: 9660717
Not possible. Cant get properties of a worksheet without opening the workbook.

LVL 24

Expert Comment

ID: 9660723
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 24

Expert Comment

ID: 9660747
(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)

Expert Comment

ID: 9663760
check this link, not the solution but some insights on getting info from a closed workbook. hope this helps

LVL 16

Expert Comment

ID: 9665171
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


Author Comment

ID: 9673807
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!

Expert Comment

ID: 9673909
Could you write a service to copy the files locally at night or something and then run the open each file exe?

LVL 16

Expert Comment

ID: 9673913
As you wish. Good luck.

Author Comment

ID: 9674223

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.


Expert Comment

ID: 9674260
Good luck!


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question