Losing the plot

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Losing the plot

Post by VegasNath »

Code: Select all

Sub test()

Dim ws As String ' not worksheet

ws = ActiveSheet.Name & " test"
'Sheets(ws).Select

With Sheets(ws)
    Range("A1") = "test"
End With

End Sub
Why am I getting the "test" result on 'sheet 1' instead of 'sheet 1 test'? It's been a long day...
:wales: Nathan :uk:
There's no place like home.....

User avatar
HansV
Administrator
Posts: 78620
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Losing the plot

Post by HansV »

Because Range("A1") refers to the active sheet. You don't specify that it belongs to Sheets(ws). To do so, change it to .Range("A1") i.e. with a period (dot) before the word Range.
Best wishes,
Hans

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Re: Losing the plot

Post by VegasNath »

Thanks Hans.
:wales: Nathan :uk:
There's no place like home.....

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Re: Losing the plot

Post by VegasNath »

I also need to check that the ws exists but I don't seem to be able to do so as ws is a string, not a worksheet? Can I have the best of both or will I need 2 declerations?
:wales: Nathan :uk:
There's no place like home.....

User avatar
HansV
Administrator
Posts: 78620
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Losing the plot

Post by HansV »

You could use code like this:

Code: Select all

Dim wsh As Worksheet
On Error Resume Next
Set wsh = Worksheets(ws)
On Error GoTo 0
If wsh Is Nothing Then
  MsgBox "The sheet " & ws & " does not exist!", vbExclamation
  Exit Sub
End If
...
Best wishes,
Hans

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Re: Losing the plot

Post by VegasNath »

Many thanks Hans.

:whisper: On Error........ This would make for an excellent tutorial!
:wales: Nathan :uk:
There's no place like home.....