Unable to select worksheet by name - vba

I'm trying to assign the first sheet of the current workbook to sheet object, but I get a Runtime error "91", Object variable or with block variable not set.
Sub Test
Dim InSheet as Worksheet
InSheet = ThisWorkbook.Sheets("Sheet1")
End Sub
However I'm able to loop through the worksheet collection like so
For Each ws in ThisWorkbook.Sheets
Debug.Print ws.Name
Next
Sheets("Sheet1") or Sheets(1) do not work. What am I doing wrong?
Any help would be greatly appreciated.
Thank you

Assuming the workbook has a sheet named "Sheet1", you just need to use Set, and better still, if you know it's a worksheet, and not a chart sheet, use Worksheets:
Sub Test
Dim InSheet as Worksheet
Set InSheet = ThisWorkbook.Worksheets("Sheet1")
End Sub
But you might find it easier to give the sheet a CodeName like InSheet in the properties window, and then you can just refer to it in code, regardless of whether somebody changes its name, like so:
Sub Test
Debug.Print InSheet.Name
End Sub

Related

VBA: Referencing a Worksheet in the Active Workbook

While this seems very basic, I am continually getting an error message while trying to select a cell in a certain sheet on my workbook in my Macro. Does any one know why this will not work? I'm getting error message Run Time Error '1004'.
The sheets name is "Sheet1"and my code is below:
Application.ActiveWorkbook.Worksheets("Sheet1").Range("N2").Select
It's bad practice to use ActiveWorkbook when you don't need to. It's always better to set your workbooks and worksheets to actual variables that you can call on. I think your code is activating another workbook then trying to select a range in a worksheet it can't find.
Sub TryThis()
Dim wbk As Workbook
Dim ws As Worksheet
Set wbk = Workbooks("myWorkbook.xlsm")
Set ws = wbk.Worksheets("Sheet1")
'Now when we say "ws." it is actually "Workbooks("myWorkbook.xlsm").Worksheets("Sheet1")."
'This is okay to start with but it's better to work with the cells directly
ws.Select
Range("N2").Select
Selection = "myText"
'This is much faster and you won't have to worry about what is currently selected
ws.Range("N2") = "myText"
End Sub

How to generate sheet from template

In VBA, i would like create a new sheet from a template after my first sheet.
Example:
In MyFirstSheet i have cell B16="House" and a button "NewSheetFromTemplate". When user click on the button a new sheet generated after my MyFirstSheet and contains same information than TEMPLATE sheet with title House.
My VBA code:
Sub NewSheetFromTemplate()
Dim sht As Worksheet
Set sht = Sheets("TEMPLATE").Copy After:=sheets("MyFirstSheet")
sht.Name = Range("B16").Value
End Sub
Excel say me "Syntax error" but why ?
I don't think is it really necessary to create Worksheet object just to rename it. Try simply like this:
Sub NewSheetFromTemplate()
Sheets("TEMPLATE").Copy After:=Sheets("MyFirstSheet")
ActiveSheet.Name = Sheets("MyFirstSheet").Range("B16").Value
End Sub
The following line of code does not return an object, one is created but this is not returned to VBA:
Sheets("TEMPLATE").Copy After:=sheets("MyFirstSheet")
This means that you cannot set this line of code to an object. Instead, try something like either of the following two options:
Using Index
Because you've copied the new worksheet after Sheets("MyFirstSheet") you can use the worksheet index of Sheets("MyFirstSheet") and then add 1 to get the sheet you've just created.
Sub NewSheetFromTemplate()
Dim sht As Worksheet
Sheets("TEMPLATE").Copy After:=sheets("MyFirstSheet")
Set sht = Sheets(Sheets("MyFirstSheet").Index+1)
sht.Name = Range("B16").Value
End Sub
Using "Name (2)"
Alternatively, the default name for a copied sheet is the original name with " (2)" tagged onto the end. This is still a useful way of identifying the new worksheet however it could become an issue if the original worksheet has a particularly long name.
Sub NewSheetFromTemplate()
Dim sht As Worksheet
Sheets("TEMPLATE").Copy After:=sheets("MyFirstSheet")
Set sht = Sheets("TEMPLATE (2)")
sht.Name = Range("B16").Value
End Sub
You can't create an instance of a Worksheet via Copy method. Since you know where are you placing the new sheet, you are able to find it after copied, and rename it. You are very close:
Sheets("TEMPLATE").Copy After:=Sheets("MyFirstSheet")
Sheets(Sheets("MyFirstSheet").Index + 1).Name = Sheets("TEMPLATE").Range("B16").Value
Make sure that you have a value in B16 range.
Hope this helps,
Cheers.

combobox with different worksheets, that changes worksheets in code

i've a question:
I would like to have a Combobox where all the worksheets are displayed. If you select a worksheet, then the worksheets in the code needs to change to the worksheet that you selected. I've tried but can't program this.
easy example:
dim WRKsheet as worksheet
set worksheet = Combobox1.value
sheets(WRKsheet).activate
Do any of you guys know how i can succeed in this?
Grts
Use the following code in a User_Form Module
Private Sub ComboBox1_Change()
' select the worksheet selected in the ComboBox1
Worksheets(ComboBox1.Value).Activate
End Sub
Private Sub UserForm_Activate()
Dim Sht As Worksheet
' show all sheets names in thisworkbook in ComboBox1
For Each Sht In ThisWorkbook.Sheets
ComboBox1.AddItem Sht.Name
Next Sht
End Sub
Note: (you need to call the form from another module, with UserForm1.Show)

How to tell if range is on activesheet or on a fixed/certain sheet?

if I
Dim rng As Range
Set rng = Range("A1")
i know rng is actually ActiveSheet.Range("A1")
then if I
Dim rngsht1 As Range
Set rngsht1 = Worksheets("Sheet1").Range("A1")
then i know rngsht1 is always on Sheet1
So now say I have a range object called "somerange", if I want to know what sheet this range is on I'll probably do this
somerange.worksheet.name
but if it gives me "Sheet1", i can't tell if it's because i have sheet1 active or because somerange is always on sheet1, without having to switch between different sheets and try again.
My question is, is there a simple way to tell whether a range object is on activesheet, or on a fixed/certain sheet? Thanks.
UPDATE: So this question is invalid. Thanks to GSerg I realized that a range object, once created, is ALWAYS on a fixed worksheet which is the worksheet the range object was created on.
Please try to use Is operator (object comparison):
If rangeObject.Worksheet Is ActiveSheet Then
' (... your code ...)
End If
Question the range's Parent
Sub MAIN()
Dim rng As Range
Set rng = Sheets(1).Range("A1")
Call IsItOnTheActiveSheet(rng)
End Sub
Sub IsItOnTheActiveSheet(r As Range)
If r.Parent.Name = ActiveSheet.Name Then
MsgBox "its on the activesheet"
Else
MsgBox "its not on the active sheet"
End If
End Sub

How to add a list of specific worksheets to the list in ComboBox VBA

I found a way to add all of the worksheets in the workbook into the list of the ComboBox on the UserForm, which is done with use of the following code
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
cmbSheet.AddItem ws.Name
Next ws
End Sub
My problem is that I only need to add some specific worksheets and not all of them. For example my user will select specific sheet and by clicking "Continue" button should end up on the selected worksheet to continue his/her task. My workbook holds several worksheets, some of which are used to output data (Reports) and some worksheets contain so called templates, which I want my user (only those) to be able to select from the ComboBox I have talked above.
Can you guys help me please?
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
if ws.Name like "*Template" then cmbSheet.AddItem ws.Name
Next ws
End Sub
perhaps you could use a naming convention for the worksheets?
if the reports you want the user to select all have the word temmplate in their name you could do something like this:
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
if instr(lcase(ws.name),"template")<>0 then
cmbSheet.AddItem ws.Name
end if
Next ws
End Sub