VBA Error if File is not found

ItalianPlatinum

Well-known Member
Joined
Mar 23, 2017
Messages
793
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
Hello,
Having issues on my VBA and couldn't seem to find anything on here that covers both of my issues. I got my VBA to error if no file with message (with below code) or proceed if their is a file (removing code). But i cant get it to do both. If no file stop and show me a error box and then the second proceed if their is a file. My code is MUCH LARGER before and after so if a file exists i need it to run further.

Dim FilePath As String
Dim TestStr As String

FilePath = "MY FILE PATH"

TestStr = ""
On Error Resume Next
TestStr = Dir("MY FILE PATH")

If TestStr = "" Then
MsgBox "File doesn't exist"
On Error GoTo -1
End If
Exit Sub

Thanks in advance for any help
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
One way.
VBA Code:
Sub TestFile()
    Dim FilePath As String
    Dim TestStr As String
    Dim FoundFile As Boolean

    FilePath = "MY FILE PATH"

    If FilePath <> "" Then
        TestStr = Dir$(FilePath)
        FoundFile = (TestStr <> "")
    Else
        FoundFile = False
    End If

    If FoundFile Then
        'execute code here


    Else
        MsgBox "File doesn't exist"
    End If
End Sub
 
Upvote 0
This pretty much worked. was getting tangled on the fact it needs to be in the start of my code. Good now.Thanks
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,249
Members
449,075
Latest member
staticfluids

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