pralufouat
pralufouat

Reputation: 1

Is there a way to trap a vba code in an error loop?

I'm working on a program using both Matlab and Excel. Excel gives its data to Matlab with a text file and then, once Matlab has finished its analysis, it creates a text file to be read by Excel.

In my vision of the program, I would like to have only one sub to do everything. Therefore, I wanted to put the sub on hold to wait Matlab until the file is ready. There comes my problem, because there's no file before Matlab finishes, trying to open the file will result in an error.

I tried to use the error handler to make a loop but it appears that VBA doesn't allow it.

Here's my test code:

Sub Test()

    Fichier = "'filepath'\file.txt"
    IndexFichier = FreeFile()
1:
    On Error GoTo expected   
    Open Fichier For Input As #IndexFichier

    Close #IndexFichier
    Exit Sub

expected:
    Err.Clear
    Close #IndexFichier 'Don't know if useful'
    GoTo 1


End Sub

I expected the code to loop between "1" and "expected" but after one loop vba breaks on its own with the expected error "file not found". Does anyone know if there's a possibility to loop on errors or do I have to make another sub?

Upvotes: 0

Views: 37

Answers (2)

Damian
Damian

Reputation: 5174

You don't need to wait for an error, this is what you are looking for:

Ruta = wb.Path & "\"
Exportar = Ruta & "datos" & Servicio & ".txt"
FindIt = Dir(Exportar)
While Len(FindIt) = 0
    FindIt = Dir(Exportar)
Wend

Upvotes: 1

Steven Carlson
Steven Carlson

Reputation: 83

You can have the code check to see if your path exists or not. If not, have it wait.

Do While Dir(Fichier) = ""
    Application.Wait(Now() + TimeValue("00:00:10"))
Loop

Upvotes: 0

Related Questions