Brian has a complex workbook that opens other supporting workbooks very briefly and then closes them, saving changes. He has an office with three people that use his macros, and on occasion they get a conflict where two people are trying to get a purchase order number at the same time. This causes the PO workbook to open in ‘read only’ mode for the second occurrence, which is confusing to users. Brian wonders if there is a line of VBA code that will stop the ‘open workbook’ command if the target workbook is already open by a different user. That way he could catch potential problems before they occur.
It is much easier to have your code, after opening, check to see if the workbook opened in read-only mode. If it did, then you can take an action appropriate to your situation. (For instance, you could close the workbook, wait a short period, and retry the operation and test.) Here’s how you can check to see the read-only status:
Set wkBook1 = Workbooks.Open("c:MyBigBook.xlsx") If wkBook1.ReadOnly Then wkBook1.Close False End If
Note that it is the ReadOnly property that yields the desired info. If you need to check the file ahead of time, you might try using some of the file-access statements available in VBA. That’s what the following function does.
Function FileIsLocked(strFileName As String) As Boolean FileIsLocked = False On Error Resume Next Open strFileName For Binary Access Read Write Lock Read Write As #1 Close #1 ' If an error occurs, the document is currently open If Err.Number 0 Then FileIsLocked = True Err.Clear End If End Function
To use the function, pass it the name (including full path) of the workbook you want to check. The function returns True if the file is locked and False if it isn’t. Remember, though, that from the time this function checks the file to the time that you actually try to open the file, it could have been opened by someone else. Thus, the first approach (checking after trying to open) may be the best approach to use.)
It should be noted, as well, that you could also save the other workbooks as shared workbooks. This would allow them to be opened by multiple users with no problems. Of course, you’ll want to check how this approach affects the data you may be wanting to save in the workbooks.