Solved

Determine .sheets.count on a Closed Excel Workbook

Posted on 2003-10-31
11
687 Views
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!
Zihif
0
Comment
Question by:Zihif
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 16

Expert Comment

by:Richie_Simonetti
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.
0
 

Accepted Solution

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

Sorry
0
 
LVL 24

Expert Comment

by:R_Rajesh
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
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100
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 WFD As WIN32_FIND_DATA
Dim Cont As Integer
If Right(path, 1) <> "\" Then path = path & "\"
nDir = 0
ReDim dirNames(nDir)
Cont = True
hSearch = FindFirstFile(path & "*", WFD)
If hSearch <> INVALID_HANDLE_VALUE Then
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)
Loop
Cont = FindClose(hSearch)
End If
hSearch = FindFirstFile(path & SearchStr, WFD)
Cont = True
If hSearch <> INVALID_HANDLE_VALUE Then
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
wkb.Close
FileCount = FileCount + 1
ActiveSheet.Cells(1, 3).Value = FileCount
ActiveSheet.Cells(FileCount, 1).Value = path & FileName
ActiveSheet.Cells(FileCount, 2) = shCnt
DoEvents
End If
Cont = FindNextFile(hSearch, WFD) ' Get next file
Wend
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
----------------------------
0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 24

Expert Comment

by:R_Rajesh
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)
0
 
LVL 2

Expert Comment

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

http://www.exceltip.com/show_tip/Files,_Workbook,_and_Worksheets_in_VBA/Read_information_from_a_closed_workbook_using_VBA_in_Microsoft_Excel/473.html
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
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.Clear
'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",
strRangeA)
        cValue2 = GetInfoFromClosedFile(FolderName, wbName, "stock",
strRangeB)
        cValue3 = GetInfoFromClosedFile(FolderName, wbName, "stock",
strRangeC)
        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
        Else
            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



0
 

Author Comment

by:Zihif
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!
Zihif
0
 

Expert Comment

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

JDSHAW
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 9673913
As you wish. Good luck.
0
 

Author Comment

by:Zihif
ID: 9674223
JDSHAW

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.

Zihif
0
 

Expert Comment

by:JDSHAW
ID: 9674260
Good luck!

JDSHAW
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
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…

803 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