I have made a macro that copies a worksheet from one workbook to another, and I have a couple questions about best practice when it comes to opening workbooks.
From previous programming experience I know that you should check to see if something is already open before trying to open it. So far that has proven true with VBA as my macro crashes if the worksheet I'm copying from was already open. I would like to know what is the best way to test if it is open. It would likely not be the active workbook and testing If Workbooks(file) Is Nothing Then ....
has given me errors. (This was what I found online as a possible solution)
If I exclude the test mentioned above I get an error on:
Set copyFromWB = Workbooks.Open(file)
Set copyFromWS = copyFromWB.Sheets(copyFromSheetName) 'ERROR HERE
when the file is already open, but it works perfectly when the file is closed. I would like to know why an error is raised when the file is already open, a 'behind the scenes' answer is really what I'm looking for here, something that explains what the computer is thinking, moreso theory.
Also on that note, I want to know why testing If Workbooks(file) Is Nothing Then ....
doesn't work for me when I've seen it being suggested on multiple VBA help forums. Is this an issue with types or does it have to do with the version of excel I am using?
For reference, "file" and "copyFromSheetName" exist and no errors arise when the file did not start from open at run-time.
Summary:
- Cleanest way to test if a workbook is open?
- Why does an already opened Workbook cause a crash when trying to access its worksheets? (I'm thinking it actually has to do with the line above
Set copyFromWB = Workbooks.Open(file)
- Why won't comparing Workbooks(file) to Nothing work? Is it a type issue, excel version issue, or something else?
I'm looking for more than a coded solution. It won't be much use to me if I don't understand why your code works and mine does not.