if file does not exist then exit VB

asylum

Board Regular
Joined
Dec 2, 2003
Messages
243
Hi,

I have a peice of code which opens up to ten work books and manipulates data.

What i need is a piece of code to put at the start which will check for the existance of each file BEFORE the rest of the code executes, if it does not exist it need to error message and exit the code at that point.

the files will all be called read 1.xls, read 2.xls etc and the 1,2, part is already stored as a variable called readno.

any good ideas? tahnks Andy
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Hi Andy

You can use Dir to test for the existence of a file:

Code:
If Len(Dir("C:\Somefolder\SomeFile.xls"))>0 Then
  'file exists - proceed accordingly
Else
  'file doesn't exist - take appropriate action
End If

So in your example it might be something like:

Code:
If Len(Dir("C:\Folder\" & readno & ".xls"))>0 Then
  Workbooks.Open "C:\Folder\" & readno & ".xls"
Else
  Exit Sub
End If
 
Upvote 0
Thanks, I have this now, but it errors as 'next without for' ??


Sub check()

For loopno = 1 To readno
If Len(Dir(strPath & "\read " & loopno & ".xls")) > 0 Then
Next loopno
Else
Exit Sub
End If

End Sub
 
Upvote 0
Next in the wrong place:

Code:
Sub check()

For loopno = 1 To readno
If Len(Dir(strPath & "\read " & loopno & ".xls")) > 0 Then

Else
Exit Sub
End If
Next loopno
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,358
Messages
6,124,487
Members
449,165
Latest member
ChipDude83

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top