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,569
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,078,520
Messages
5,340,922
Members
399,399
Latest member
SravanaSandhya

Some videos you may like

This Week's Hot Topics

  • Problem with Radio Button's format control
    I am creating an employee evaluation template (a sample is below) Column A is the category Column B, C D, E and F will be ratings (unacceptable...
  • Last Display on userform to a Listbox
    [CODE=vba] lstdisplay.ColumnCount = 15 lstdisplay.RowSource = "A1:O600000" [/CODE] So when i do this it Displays everything on the sheet i am...
  • Rename and move files to a new location
    Dear all, I have an excel file with the following information. The actual file name is at column A but i want to rename it using the following...
  • Help with True/False Formula
    Hello! Am stumped how to fix this formula, in which my result returns 'True', but it should return False. =IF(AG2=True...
  • Clear extra characters from a provided range of cells
    Dear All, I have following code which gives me desired output to remove extra characters from a provided range. But it takes too much time when...
  • Help with Current and highest streaks
    Hi there, I've just joined the forum and this is my first post. I've already spent quite a bit of time searching the net and this forum for a...
Top