How check if file to open is Excel or if Excel file is corrupt?

I'm using Excel 2003.   I'm looping through a set of Excel files, opening 
each one and writing data from that Excel spreadsheet into a "master" excel 
spreadsheet.  

The program failed when one of the Excel files was corrupt.  
Also--occasionally the user will have a file in a different format (e.g., 
Word) in the directory I'm working with, and that's causing problems.

1)  How do I check that the file to be opened IS .xls?
2)  How do I check that the Excel file is not corrupt?

Your help would be GREATLY appreciated.

THANKS!

0
Utf
11/19/2009 6:47:02 PM
excel.programming 6508 articles. 2 followers. Follow

4 Replies
950 Views

Similar Articles

[PageSpeed] 16

Hi,

I would do this with 2 subs, the first to open each .xls file in turn and 
the second to do whatever it is you want. Change the path in the first sub to 
your path. The second sub in my samp;e code simply displays the filename.

Sub LoopThroughDirectory()
Application.DisplayAlerts = False
'Change this to your directory
MyPath = "C:\"
ActiveFile = Dir(MyPath & "*.xls")
Do While ActiveFile <> ""
   Workbooks.Open Filename:=MyPath & ActiveFile
   'Here is the line that calls the macro below, passing the workbook to it
   DoSomething ActiveWorkbook
   ActiveWorkbook.Save
   ActiveWorkbook.Close
   ActiveFile = Dir()
Loop

Application.DisplayAlerts = True
End Sub

Sub DoSomething(Book As Workbook)
MsgBox ActiveWorkbook.Name
End Sub

Mike


"laavista" wrote:

> I'm using Excel 2003.   I'm looping through a set of Excel files, opening 
> each one and writing data from that Excel spreadsheet into a "master" excel 
> spreadsheet.  
> 
> The program failed when one of the Excel files was corrupt.  
> Also--occasionally the user will have a file in a different format (e.g., 
> Word) in the directory I'm working with, and that's causing problems.
> 
> 1)  How do I check that the file to be opened IS .xls?
> 2)  How do I check that the Excel file is not corrupt?
> 
> Your help would be GREATLY appreciated.
> 
> THANKS!
> 
0
Utf
11/19/2009 7:01:01 PM
This is a bit of a long answer, but it works well for us in a similar scenario.

Sub Test_File_Access()

    cFile = ' set to the name of the file you need to activate
    cDirect = ' set to the folder containing the files

    lClose = False
    lOpen = ZZZZ_SelectFile(cFile)
    If lOpen = False Then
        lClose = True
        lOpen = ZZZZ_OpenFile(cFile, cDirect, True, False, False)
        If lOpen = False Then
            n = MsgBox("Expected file not found", vbInformation)
            Exit Sub
        End If
    End If
' Do your stuff here

' The next bit closes the data file again (otherwise you end up with masses 
of files opened)
    If lClose = True then
        Application.CutCopyMode = False
        Windows(cFile).Activate
        ActiveWorkbook.Close (False)
    End If

End Sub

Function ZZZZ_OpenFile(pFile, pDirect, pReadOnly, pUpdateLinks, pMessage)
' Attempts to open a specified file
' Returns True if the operation was successful
' Returns False if the operation failed
' pFile is the file to be opened
' pDirect is the directory in which the file is to be found
' pReadOnly determines whether the file is to be opened read only
' pUpdateLinks determines whether any file links are updated when opening
' pMessage detgermines whether s fail message is displayed to the user

' Set ZZZZ_OpenFile to true - it will be reset to false if the operation fails
    ZZZZ_OpenFile = True
' cOpenFile is the full path and filename to be opened
    pOpenFile = Trim(pDirect) + Trim(pFile)
' Set error trap to capture a failure to open
    On Error GoTo NotOpen
' Atempt to open the specified file
    Workbooks.Open Filename:=pOpenFile, ReadOnly:=pReadOnly, 
UpdateLinks:=pUpdateLinks
' Reset the error trap to Excel defaults
    On Error GoTo 0
' If the operation failed and messages are to be displayed
    If ZZZZ_OpenFile = False And pMessage = True Then
' Display the message to the user
        nResponse = MsgBox(pOpenFile + " doesn't exist", vbCritical)
    End If
    Exit Function
NotOpen:
' Reset ZZZZ_OpenFile to false when the operation fails
ZZZZ_OpenFile = False
Resume Next
End Function

Function ZZZZ_SelectFile(pFile)
' Attempts to select a specified file
' Returns True if the operation was successful
' Returns False if the operation failed
' pFile is the file to be selected
' Set ZZZZ_SelectFile to true - it will be reset to false if the operation 
fails
    ZZZZ_SelectFile = True
' Set error trap to capture a failure to select
    On Error GoTo NotOpen
' Select the specified file
    Windows(pFile).Activate
' Reset the error trap to Excel defaults
    On Error GoTo 0
    Exit Function
NotOpen:
' Reset ZZZZ_OpenFile to false when the operation fails
ZZZZ_SelectFile = False
Resume Next
End Function






"laavista" wrote:

> I'm using Excel 2003.   I'm looping through a set of Excel files, opening 
> each one and writing data from that Excel spreadsheet into a "master" excel 
> spreadsheet.  
> 
> The program failed when one of the Excel files was corrupt.  
> Also--occasionally the user will have a file in a different format (e.g., 
> Word) in the directory I'm working with, and that's causing problems.
> 
> 1)  How do I check that the file to be opened IS .xls?
> 2)  How do I check that the Excel file is not corrupt?
> 
> Your help would be GREATLY appreciated.
> 
> THANKS!
> 
0
Utf
11/19/2009 7:05:01 PM
Thanks.  I'm able to open and loop through the spreadsheets, but it fails 
when the excel file is corrupt or if it tries to open a non-Excel file.

"Mike H" wrote:

> Hi,
> 
> I would do this with 2 subs, the first to open each .xls file in turn and 
> the second to do whatever it is you want. Change the path in the first sub to 
> your path. The second sub in my samp;e code simply displays the filename.
> 
> Sub LoopThroughDirectory()
> Application.DisplayAlerts = False
> 'Change this to your directory
> MyPath = "C:\"
> ActiveFile = Dir(MyPath & "*.xls")
> Do While ActiveFile <> ""
>    Workbooks.Open Filename:=MyPath & ActiveFile
>    'Here is the line that calls the macro below, passing the workbook to it
>    DoSomething ActiveWorkbook
>    ActiveWorkbook.Save
>    ActiveWorkbook.Close
>    ActiveFile = Dir()
> Loop
> 
> Application.DisplayAlerts = True
> End Sub
> 
> Sub DoSomething(Book As Workbook)
> MsgBox ActiveWorkbook.Name
> End Sub
> 
> Mike
> 
> 
> "laavista" wrote:
> 
> > I'm using Excel 2003.   I'm looping through a set of Excel files, opening 
> > each one and writing data from that Excel spreadsheet into a "master" excel 
> > spreadsheet.  
> > 
> > The program failed when one of the Excel files was corrupt.  
> > Also--occasionally the user will have a file in a different format (e.g., 
> > Word) in the directory I'm working with, and that's causing problems.
> > 
> > 1)  How do I check that the file to be opened IS .xls?
> > 2)  How do I check that the Excel file is not corrupt?
> > 
> > Your help would be GREATLY appreciated.
> > 
> > THANKS!
> > 
0
Utf
11/19/2009 8:18:02 PM
Thank you so much.  This is great and is what I needed.

I really appreciate you taking the time to post the answer!

"Paul" wrote:

> This is a bit of a long answer, but it works well for us in a similar scenario.
> 
> Sub Test_File_Access()
> 
>     cFile = ' set to the name of the file you need to activate
>     cDirect = ' set to the folder containing the files
> 
>     lClose = False
>     lOpen = ZZZZ_SelectFile(cFile)
>     If lOpen = False Then
>         lClose = True
>         lOpen = ZZZZ_OpenFile(cFile, cDirect, True, False, False)
>         If lOpen = False Then
>             n = MsgBox("Expected file not found", vbInformation)
>             Exit Sub
>         End If
>     End If
> ' Do your stuff here
> 
> ' The next bit closes the data file again (otherwise you end up with masses 
> of files opened)
>     If lClose = True then
>         Application.CutCopyMode = False
>         Windows(cFile).Activate
>         ActiveWorkbook.Close (False)
>     End If
> 
> End Sub
> 
> Function ZZZZ_OpenFile(pFile, pDirect, pReadOnly, pUpdateLinks, pMessage)
> ' Attempts to open a specified file
> ' Returns True if the operation was successful
> ' Returns False if the operation failed
> ' pFile is the file to be opened
> ' pDirect is the directory in which the file is to be found
> ' pReadOnly determines whether the file is to be opened read only
> ' pUpdateLinks determines whether any file links are updated when opening
> ' pMessage detgermines whether s fail message is displayed to the user
> 
> ' Set ZZZZ_OpenFile to true - it will be reset to false if the operation fails
>     ZZZZ_OpenFile = True
> ' cOpenFile is the full path and filename to be opened
>     pOpenFile = Trim(pDirect) + Trim(pFile)
> ' Set error trap to capture a failure to open
>     On Error GoTo NotOpen
> ' Atempt to open the specified file
>     Workbooks.Open Filename:=pOpenFile, ReadOnly:=pReadOnly, 
> UpdateLinks:=pUpdateLinks
> ' Reset the error trap to Excel defaults
>     On Error GoTo 0
> ' If the operation failed and messages are to be displayed
>     If ZZZZ_OpenFile = False And pMessage = True Then
> ' Display the message to the user
>         nResponse = MsgBox(pOpenFile + " doesn't exist", vbCritical)
>     End If
>     Exit Function
> NotOpen:
> ' Reset ZZZZ_OpenFile to false when the operation fails
> ZZZZ_OpenFile = False
> Resume Next
> End Function
> 
> Function ZZZZ_SelectFile(pFile)
> ' Attempts to select a specified file
> ' Returns True if the operation was successful
> ' Returns False if the operation failed
> ' pFile is the file to be selected
> ' Set ZZZZ_SelectFile to true - it will be reset to false if the operation 
> fails
>     ZZZZ_SelectFile = True
> ' Set error trap to capture a failure to select
>     On Error GoTo NotOpen
> ' Select the specified file
>     Windows(pFile).Activate
> ' Reset the error trap to Excel defaults
>     On Error GoTo 0
>     Exit Function
> NotOpen:
> ' Reset ZZZZ_OpenFile to false when the operation fails
> ZZZZ_SelectFile = False
> Resume Next
> End Function
> 
> 
> 
> 
> 
> 
> "laavista" wrote:
> 
> > I'm using Excel 2003.   I'm looping through a set of Excel files, opening 
> > each one and writing data from that Excel spreadsheet into a "master" excel 
> > spreadsheet.  
> > 
> > The program failed when one of the Excel files was corrupt.  
> > Also--occasionally the user will have a file in a different format (e.g., 
> > Word) in the directory I'm working with, and that's causing problems.
> > 
> > 1)  How do I check that the file to be opened IS .xls?
> > 2)  How do I check that the Excel file is not corrupt?
> > 
> > Your help would be GREATLY appreciated.
> > 
> > THANKS!
> > 
0
Utf
11/19/2009 8:19:01 PM
Reply:

Similar Artilces:

Check current cell is empty
Hi, I'm getting stuck... If I enter some new data in Sheet2, column A, then this cell will be copied to last cell of sheet 1 columnA automatically. This task can be done now IF the data is overwriting some existing data, no need to copy. my logic is if the active cell is empty, and the target column is 1, then do the copy and paste. else, do nothing The question is: how can I check the current cell is empty? Thank you in Advance Bobocat Sub tester() If IsEmpty(ActiveCell) Then MsgBox "Activecell Is Empty" Else MsgBox "Activecell Is Not Empty&quo...

VBA
Hi! I have a template where I have allowed users to insert rows. I use the following code: Range("a52").Select Selection.EntireRow.Insert Rows("53:53").Copy Rows("52:52").Select Selection.PasteSpecial Paste:=xlFormulas, Operation:=xlNone, SkipBlanks:= False, Transpose:=False Range("a2").Select However, when the user closes the file - there is a huge amt of data on the clip board and I do not want the user to get the message - is there a way for me to clear the information on the clip board? Also what does "Applica...

Auto-format in Microsoft Excel.
Each time i try to enter a number range, for example, 8- 10, in Excel, it constantly re-formats it to a date. If I change the formatting to "General" it turns it into a random number, usually 38209. I would like to turn off ALL auto-formatting, but that's probably asking too much. How do I disable this frustrating feature? thanks. Hi Paul When you enter "8-10" in a cell, that's not strictly a number but Excel thinks you mean a date so converts it as such. A date is a number and in your example the number 38209 represents August 10 2004 which is not a ra...

MS Money 95 data files
I hope that some one can answer this for me. I have used MS Money 95 for years, and it works just fine for me on Windows XP, however, I now have to reformat my hard drive, and have discovered that I can nolonger find my original install disk. Will the latest versions of Money still read the MS Money 95 data files. All that I have ever used the program for is to track my investments, and am unlikely to do any different in the future. Thanks Stan B In microsoft.public.money, Stan Banner wrote: >I hope that some one can answer this for me. >I have used MS Money 95 for years, and...

function to check for entry
I'll try and make this as clear as I can... I am looking for a function that will check column b,c,d,e for an entr if there is an entry then check row n in the same row for it's value. that's the first bit, then I need to be able to check the date valu (month) in column a and total it for the month. perhaps I could run the first function only looking for month=1 o something and just run it 12 times? not sure how to go about this -- Message posted from http://www.ExcelForum.com well I've got this far but it still doesn't work and gives an error: =IF(MONTH(A3:A167)=4,...

Excel not Access
I have designed an Access database that holds records relating to my stores audit results going back for about 5 years plus a load more information relating to these stores. This was used to produe a pack once a month, however a change in senior management means that I have got to shelve this and prodce a similar pack in Excel. The idea would be that the user could select a month or a 12 mnth date range that would produce data that could then be used to populate a number of excel templates that have been designed. Having not used excel for years I would be grateful for any suggestion...

How to keep format when importing Excel into SQL.
Can anybody help me please? When I import Excel file into SQL, a field that formated as 0000000000 (custom), loosing leading zeros. I tried to change data type in SQL after importing. No luck. I appretiate any help. See if using IMEX=1 helps: http://pratchev.blogspot.com/2007/10/importing-excel-data-into-sql-server.html -- Plamen Ratchev http://www.SQLStudio.com Plamen, I tried this, but got an error: "The OLE DB provider "Microsoft.Jet.OLEDB.4.0" has not been registered." Thank you very much for looking into this. "Plamen Ratchev" wr...

Outlook 2003 and "Check Names"
Hi, We are testing Outlook 2003 at our office now and there is one very frustrating "feature" that is bugging all of us. When we create a new e-mail message and type in the first name of a person from the global address book and hit ctrl- k to check the name...we get a response that Outlook doesn't recognize the name and there are "no suggestions". The only way Check Name will successfully resolve the name is if we type it last name first (ie, Gates, Bill). This was not the case in Office XP or Outlook 2000. You could search by first name (or partial first name)...

Input Excel 'Password to Open' through control in access form
Hi All, We know,Excel has prompt password to open it files. Is it possible to create a code that can supplies the excel prompt password?.So that when we open the excel file through our access control in a form, the excel files can be opened automatically.But when the excel files opened from its default icon,it will prompt a password first. ...

Excel 2007
When I select cells to copy as a picture in Excel 2007, the resolution is terrible. Text and objects with shadow's are very blotchy when pasting the picture. How do you change the resolution of a 'Copy Picture'? ...

How To Copy MS Word mailing labels into Excel
I have a word doc that I want to put into Excel. I want to add some more fields to the names and addresses. Is this simple or do I have to learn how to program? Michael Rodriguez City of Grand Prairie Michael, have you tried to copy and paste the data into excel? -- Paul B Always backup your data before trying something new Please post any response to the newsgroups so others can benefit from it Feedback on answers is always appreciated! Using Excel 2000 & 97 ** remove news from my email address to reply by email ** "Michael Rodriguez" <mrodrigu@gptx.org> wrote in messa...

Grammar check not working
Hello, I am using Word 2007 and have a problem with grammar and punctuation errors. I deliberately put two spaces between words, do not put space after a comma, write long sentences and finish a sentence without a verb but the green underline never appears. The spell check is functioning properly, no problem with that. In Word Options > Proofing, "Mark grammar errors as you type" is selected. I changed that selection and tried again but it still did not work. I used different languages as default language but no change. I would be grateful if someone could come...

How do I use traffic lights in excel
I am wanting to use traffic lights in excel that change colour based on the result of a variance cell, ie if the result of the cell is 10 make the traffic light green, if it is 20 make the traffic light amber, if the result is 30 make the traffic light red. How do I do this? Shorty Format>Conditional Formatting>Cell Value is: Note: you can add up to 3 conditions(4 if you count default) Gord Dibben Excel MVP On Wed, 22 Dec 2004 16:35:03 -0800, Shorty <Shorty@discussions.microsoft.com> wrote: >I am wanting to use traffic lights in excel that change colour based on the &g...

Drag and Drop file/directory names on Tree Control.
hi, I am writing an application in which i have one Tree control. Now i want that , when user drag & drop any file/folder on tree control the file name/folder name should be add in the tree control item. User may drag and drop file from desktop or may be from directory. I just want the path of that file/foder name nothing else. so plz tell me will it be possible ... Plz Help me............. Klic..... > I am writing an application in which i have one Tree control. >Now i want that , when user drag & drop any file/folder on tree >control the file nam...

Planned Open Market Days
A spreadsheet named "NYSE Holidays" contains NYSE Planned Holidays for 2005 and 2006; containing data in columns A and B: New Year's Day 01/01/05 Martin Luther King, Jr. Day 01/17/05 Washington's Birthday 02/21/05 Good Friday 03/25/05 Memorial Day 05/30/05 Independence Day 07/04/05 Labor Day 09/05/05 Thanksgiving Day 11/24/05 Christmas 12/26/05 New Year's Day 01/02/06 Martin Luther King, Jr. Day 01/16/06 Washington's Birthday 02/20/06 Good Friday 04/14/06 Memorial Day 05/29/06 Independence Day 07/04/06 Labor Day 09/04/06 Thanksgiving Day 11/23/06 Christmas 12/25/06 ...

Unexpected error message on closing an Excel file
Suddenly I am getting the following message when I try to close a workbook: "Your formula contains an invalid external reference to a worksheet. Verify that the path, workbook, and range name or cell reference are correct, and try again" The mysterious thing is that it does not happen consistently and that, after I click OK after the above message, I can still save the file. What might be the cause of this error message and can the "invalid reference" be tracked down using one of the utility add-ins such as J. Walkenbach's PUP? If it only happens when you close ...

cant start outlook pst file to large
Hi I hope somebody may be able to help im new to outlook and now I cant start outlook message says cannot open your default email folders pst file its too large as I cannot open outlook I cannot delete old folders See if this helps: http://support.microsoft.com/kb/296088 -- -Ben- Ben M. Schorr, MVP Roland Schorr & Tower http://www.rolandschorr.com http://www.officeforlawyers.com/outlook.html Author: The Lawyer's Guide to Microsoft Outlook 2007: http://tinyurl.com/ol4law-amazon "Ray" <Ray@discussions.microsoft.com> wrote in message news:B3B824DC-3C9B-4B1B-8EF3-61...

help with simple maths in excel
I want to do a simple arithmatic excercise in excel for my grand daughter. It is stuff like 2+2 =4 Smart me has hit a problem at the first hurdle... I need to put 2 in one cell the + in another cell and then 2 in another = in another and then she puts the answer in the next one. So the above would have 4 cells completed and she would put the answer in the 5th one. When I use the + or = sign in a cell of its own it (excel) thinks I am doing an equation, is there a way around this? I will work on the answer like if she gets it correct or wrong how I will do that...a sound or som...

Where is the workspace file stored?
I was given a project folder containing several dozen files. So where is the workspace file normally located? If I don't have a workspace file how can I cerate one? Using VC version 6. TIA I haven't used VC6 for some time, but if I remember right you can just open the .dsp file and it will create a .dsw file for you. It typically goes in the same folder with the code. Tom "Phisherman" <noone@nobody.com> wrote in message news:be93539ccf8a6f25ibh4vt6ggmtbi024mq@4ax.com... >I was given a project folder containing several dozen files. So where > is the wor...

How to change font size on formula bar in Excell 2007
I don't find Tools>Options>General (as suggested in other post answers) in Excel 2007. On the Office button there is an Excel Options but it doesn't provide a method of changing font size on the office but. My font is so small I can barely see it. Office button>ExcelOptions>Popular tab>in the "When creating new workbooks" section, choose font and font size -- Kind regards, Niek Otten Microsoft MVP - Excel "jimwillie" <jimwillie@discussions.microsoft.com> wrote in message news:588AAC05-0F52-404E-AA01-128E70E02D0B@microso...

Change File Locations to Private Drive (not Folder)
Hi, I know that I can use "File Locations" in "Options" so that whenever I use the "Open..." command in Word, it will open to a specific folder. I'm wondering if there is a way that this can be applied not to a folder but to a specific drive on a network. Our company has a main public drive and has also assigned each of the Staff their own private drive. Is there a way to access the "main page" (for lack of a better term) of my private drive each time I use "Open..." in Word? Right now it goes to "My Computer" or ...

Invalid XML error when I open customization setting
I have a problem when I try to open customization setting after I import an entity. The system errored "Invalid XML" "The XML passed to the platform is not well-formed XML". Please recommend how to resolve this problem. Thanks. ...

Opening Excel Workbooks
I'm running into an issue where if I click on an Excel file through My Documents, it doesn't automatically bring it up. I get the toolbar but the actual spreadsheet doesn't appear on the screen. I have to click on the taskbar to get it to pop up. If I already have Excel active and I open a file through Excel, this doesn't happen. Any ideas? Here is a similar thread: http://www.excelforum.com/showthread.php?s=&threadid=237195 Rolli -- Message posted from http://www.ExcelForum.com Hi, Take a look at Tools-Options-General tab- uncheck ignore other application...

Excel DNS query
Hello, Is there a way for an Excel function to query a DNS server? Thanks. Soundy Not that I know of, but you can turn on the macro recorder, use 'get external data' and tailor the resulting code into a user function of your own. E.g. I've used this to create a button to get MS-Access data from a query that has the same name as the sheet (tab) name. It saves me a lot of copy-paste actions. Bas Hartkamp <soundy@gmail.com> schreef in bericht news:1151940450.029823.127570@j8g2000cwa.googlegroups.com... > Hello, > > Is there a way for an Excel function ...

[b]Can I download Excel data to a MS Access database?[/b]
I've built an Excel 2002 form that I want our internal customers to access from our intranet, and use. Once completed, they will send it to us as an e-mail attachment. I'd like to be able to open it, and somehow download the data from the form into an MS Access 2002 database I've built (so that we don't have to rekey it into the database). Is this possible or even feasible? Any and all help is appreciated. Thanks. :D --------- Message sent via www.excelforums.com Hi in Access check 'File - Import External data' -- Regards Frank Kabel Frankfurt, Germany "...