I virtually never define a variable as a workbook , a worksheet or a range. I much prefer to use variant arrays as much as possible. This means that I very rarely use the instruction format :
Set CS= ….. some object of workbook, worksheet , rangetype.
Although it is very much frowned upon by lots of the experts on these forums, I prefer to use activate and select to access workbooks and worksheets, the reason for this is it simplifies the syntax for correctly addressing workbooks, worksheets and ranges and helps in debugging. I acknowledge that it can be quicker to use the “With” construct, but since I already know how to write lightning fast code by using variant array all the time, the time taken for one or two activates and selects is negligible. I do totally accept that many people will use activate and select in a very inefficient way.
So the way I address lots of different sheets and workbooks is simple, I do it in a very similar way to a human, when I open a workbook , I remember it’s name, when I want to use a worksheet I select the worksheet. This has a great advantage when debugging the system because when you put a breakpoint in, when I swap to the EXCEL window, if I have activated a workbook and selected a worksheet, then that is what appears. If the wrong sheet appears I know the code is wrong. ( This is one of the reasons I prefer activate and select)
So the code I used moving between workbooks and worksheets is as follows:
At the top of the Master workbook I have the code line:
Code:
CurrentWorkbookName = ActiveWorkbook.Name
when opening the client workbook the code is:
Code:
Workbooks.Open Filename:=newf
‘ This new workbook is now the active workbook so I save the workbook name
NewWorkbookName = ActiveWorkbook.Name
Worksheets("Financial").Select
I can then reference individual cells on this sheets simply:
Similar with ranges
I then swap back to the Master workbook and a specific worksheet with this code
Code:
Windows(CurrentWorkbookName).Activate
Worksheets(monm).Select
Once again I can reference cells and ranges with the simplest of lines as above.
I find using these very simple methods, means I very rarely struggle with getting the correct syntax. Everytime I try using syntax that depends on setting some variable to a worksheet or workbook or even using the WITH construct I usually end up with some error. This is probably because I am a programmer who uses EXCEL rather than a EXCEL expert