Opening multiple workbooks causes identity issues

insomniac53

Board Regular
Joined
Sep 3, 2013
Messages
104
When opening more than one workbook in Excel (latest Office 365 version) VBA code does not know which workbook it belongs to. For example, suppose you have two workbooks open and you switch from one to the other, perhaps using ALT-TAB. Any procedures or functions referring to a particular sheet will crash because it's looking in the active workbook, not the one it belongs to.

Code:
Private Function MyFunction() As integer
    Dim w1 As Worksheet: Set w1 = Sheets("name of sheet")
    <code>*** code ***
End Function

This is fine until another workbook has been opened at which point the code fails, even if this is the active one on screen. I understand that you could specify a workbook and sheet within a single function, but this isn't feasible when you have many functions using the simple Sheets command above - you would need to alter each one individually.

Could someone tell me if there is a way around this on a global level so that when switching from workbook to workbook, the vba code knows which one it belongs to? Thanks!</code>
 

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.

Forum statistics

Threads
1,223,246
Messages
6,170,996
Members
452,373
Latest member
TimReeks

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