VBA if ReadOnly Loop

zodiaceuk

Board Regular
Joined
Nov 20, 2011
Messages
103
Hi All,

Hoping someone can help me with this.
I have some code that will open another Workbook, add data, save/close.

I’m trying to create a loop that will check if the file is opened read only, if the file is opened read only, if like it to close the file and try to open it again, after 5 failed attempts display a message box and stop the code.

This is what I’ve came up with, however, the code seems to run continually, without taking the 5 attempts into account.

Can you help me find where I’ve gone wrong please?

Code:
Dim wb1 as workbook
Dim attempts as interger 

Attempts = 0

Start1:
Set wb1 = workbooks.open(filename:=“c:\temp\myfile.xls”)

Do until wb1.ReadOnly = False or Attempts > 5
Attempts = Attempts + 1
 If wb1.readonly then
 Wb1.close
 Application.wait (now + TimeValue(“00:00:01”)     If Attempts > 5 then 
Msg box “Failed, to many attempts”
Exit sub
End if
Goto start1
End if
Loop
Thanks for any help ?
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
30,213
Office Version
365
Platform
Windows
I'm surprised that code even runs, it's normally best to copy & paste your actual code, rather than typing it into the post. That said, after correcting all the problems, it works for me.
If you step through the code using F8, what happens when "Attempts" equals 6?
 

Forum statistics

Threads
1,077,784
Messages
5,336,328
Members
399,076
Latest member
vullistax

Some videos you may like

This Week's Hot Topics

Top