Determine .sheets.count on a Closed Excel Workbook

Posted on 2003-10-31
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

Comment Utility
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 100 total points
Comment Utility
Not possible. Cant get properties of a worksheet without opening the workbook.

LVL 24

Expert Comment

Comment Utility
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
LVL 24

Expert Comment

Comment Utility
(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

Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

LVL 16

Expert Comment

Comment Utility
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

Comment Utility
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

Comment Utility
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

Comment Utility
As you wish. Good luck.

Author Comment

Comment Utility

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

Comment Utility
Good luck!


Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

762 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now