specify workbook in VBA

depcdivr

Active Member
Joined
Jan 21, 2008
Messages
350
Office Version
  1. 365
Platform
  1. Windows
I am running into a minor inconvience and I am sure that there is a simple fix to is.

I am running a userform from a workbook that will most likely be left open for extended periods of time. If the userform is left open and the user switches to a different workbook the form errors because it may be looking for a sheet that does not exits.

I use the following code to define the sheet but how can I specify workbook that it is to look in?

Code:
Set ws = Worksheets("Training Data")
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
The userform is modal. Is there any reason that it should be modal? The non-modal userform will not let you access excel while you are working on it.
 
Upvote 0
I set the userform to modal because otherwise people will not use it. THey like to be able to switch back and forth between programs at will. If I prevent them from doing this the program will not get used.
 
Upvote 0
If the name of the workbook where this userform is located is fixed then
Code:
Set ws = Workbooks("[I]MyMacroBK[/I]").Worksheets("Training Data")
or if the name is something that people change to suit then use some variable like:
Code:
Dim sName as String
sName = ThisWorkBook.Name
Set ws = Workbooks(sName).Worksheets("Training Data")
 
Upvote 0

Forum statistics

Threads
1,224,521
Messages
6,179,289
Members
452,902
Latest member
Knuddeluff

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