Using a variable for worksheet name

BeechamC

New Member
Joined
Nov 7, 2013
Messages
10
Hi all - first, let me say this is an enormously helpful forum! For weeks I've found every answer I needed without even registering. I will be sure to contribute back as/when I'm able!

I have an issue using a variable as a worksheet name. I have code finding the first name of a user from Application.Username, and then I want to call a worksheet specific to this person. Current code:

Dim UName As String
Dim unameSplit As Variant
Dim UFN As String

UName = Application.UserName

unameSplit = Split(UName, ",")
UFN = unameSplit(1)

Set wstemp = Sheets(UFN)


I currently get error "Subscript out of range" when running. If I change wstemp to Sheets("Peter") it works however. What am I doing wrong?
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Welcome to MrExcel.

Does this work for you?

Code:
Dim UName As String
Dim unameSplit As Variant
Dim UFN As String
UName = Application.UserName
unameSplit = Split(UName, " ")
UFN = unameSplit(0)
 
Upvote 0
Thanks. The problem doesn't seem to be how UFN is defined/created, because UFN's value in my code is Peter when tested in a label. The problem seems to be in setting the worksheet as the variable UFN rather than a string like "Peter"... flummoxed!
 
Upvote 0
Yes, I get the exact same "Subscript out of range" error message. Does the worksheet collection only accept limited types of input perhaps?
 
Upvote 0
You need to remove the leading space:

Rich (BB code):
Sub T()
    Dim UName As String
    Dim unameSplit As Variant
    Dim UFN As String
    UName = Application.UserName
    unameSplit = Split(UName, ",")
    UFN = Trim(unameSplit(1))
    Set wstemp = Sheets(UFN)
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,920
Messages
6,122,264
Members
449,075
Latest member
staticfluids

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