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 ?
 

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop
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?
 
Upvote 0

Forum statistics

Threads
1,214,524
Messages
6,120,049
Members
448,940
Latest member
mdusw

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