Access Worksheet by name including ThisWorkbook - excel

This has been bothering me for a while. I want to access Worksheet by name instead of "how worksheet has been named in Excel". I would like also to include ThisWorkbook in the line, to eliminate possibility of having several Workbooks open with Worksheets with the same name. However I am getting an error:
I have named my Worksheet CalculationItem1. Why following does not work?
Sub TestTest()
ThisWorkbook.CalculationItem1.Range("A1:A2").Copy
End Sub
Following error appears:
Following works but there is a possibility of having same named Worksheet in another opened Workbook? Then errors can appear?
Sub TestTest()
CalculationItem1.Range("A1:A2").Copy
End Sub
Here is the name:

As long as the sheet is in the same Workbook as the code ("ThisWorkbook"), you can access the sheet via it's code name. That is true even if the Workbook is not active - it's like you have an object-variable with that name. So using CalculationItem1.Range("A1:A2").Copy will always refer to the sheet with the code name CalculationItem1 of ThisWorkbook.
If you want to access a worksheet of another workbook via code name, you have to iterate the sheets and look for the property CodeName (as FaneDuru shows in his answer).

Not sure that is possible to directly define the sheet using a specific CodeName.
But you can avoid confusing about such a sheet and another one of the active workbook, similarly named, using a function like this:
Function SetShByCN(strCodeName As String, wb As Workbook) As Worksheet
Dim sh As Worksheet
For Each sh In wb.Worksheets
If sh.CodeName = strCodeName Then Set SetShByCN = sh: Exit Function
Next
End Function
It must be adapted to send a warning in case of not existing such a sheet, or to return Nothing and this to be checked in the code calling the function. This is only made for testing reason...
It will do the job being called like in the next test code:
Sub testSetShByCN()
Dim wks As Worksheet
Set wks = SetShByCN("CalculationItem1", ThisWorkbook)
Debug.Print wks.Name
sh.Range("A1:A2").Copy
End Sub

In your first piece of code, you need to tell Excel that you are referring to a worksheet:
Sub TestTest()
ThisWorkbook.WorkSheets("CalculationItem1").Range("A1:A2").Copy
End Sub
Regards,

Related

insert and fill out new columns - error in code [duplicate]

During the process of running a script if I manually remove focus from the Workbook containing the macro I get the error quoted. If I don't click on anything it works without issue. Script errors out only when I'm trying to place selection back into A1 from the "Input" sheet. Break point is on following line:
ThisWorkbook.Sheets("Input").Range("A1").Select
If I debug and place focus back on macro Worksheet the script completes without issue. Previous line:
ThisWorkbook.Sheets("Input").Cells.Delete
runs without error so I'm guessing its the range that is falling out of scope but don't quite understand why as it should be defined by the previous scope notations.
Can someone explain why that line is falling out of scope? Shouldn't the ThisWorkbook define fairly explicitly the Workbook that my code is referencing? Any guidance is greatly appreciated.
It doesn't have anything to do with the reference to ThisWorkbook at all. You simply can't Select a Range in an object that isn't active. Consider this code, which exhibits the same error:
Private Sub OneOhOhFour()
'Executing with Book1.xlsm active and Book2.xlsx open.
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
Debug.Print ThisWorkbook.Name
'Outputs 'Book1.xlsm' to Immediate window.
wb.Sheets("Sheet1").Range("A1").Select 'Error 1004
End Sub
Same thing with Worksheets:
Private Sub OneOhOhFourVTwo()
'Starting on anywhere but Sheet2 gives an error.
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1").Select 'Error 1004.
End Sub
The simple solution is to Activate the object before you Select within it:
Private Sub NoOneOhOhFour()
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
wb.Activate
wb.Sheets("Sheet1").Range("A1").Select 'No error.
End Sub
Even better is using references and trying to avoid using the Selection and Active* objects entirely.

How do you select a specific cell on a specific sheet excel VBA? [duplicate]

During the process of running a script if I manually remove focus from the Workbook containing the macro I get the error quoted. If I don't click on anything it works without issue. Script errors out only when I'm trying to place selection back into A1 from the "Input" sheet. Break point is on following line:
ThisWorkbook.Sheets("Input").Range("A1").Select
If I debug and place focus back on macro Worksheet the script completes without issue. Previous line:
ThisWorkbook.Sheets("Input").Cells.Delete
runs without error so I'm guessing its the range that is falling out of scope but don't quite understand why as it should be defined by the previous scope notations.
Can someone explain why that line is falling out of scope? Shouldn't the ThisWorkbook define fairly explicitly the Workbook that my code is referencing? Any guidance is greatly appreciated.
It doesn't have anything to do with the reference to ThisWorkbook at all. You simply can't Select a Range in an object that isn't active. Consider this code, which exhibits the same error:
Private Sub OneOhOhFour()
'Executing with Book1.xlsm active and Book2.xlsx open.
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
Debug.Print ThisWorkbook.Name
'Outputs 'Book1.xlsm' to Immediate window.
wb.Sheets("Sheet1").Range("A1").Select 'Error 1004
End Sub
Same thing with Worksheets:
Private Sub OneOhOhFourVTwo()
'Starting on anywhere but Sheet2 gives an error.
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1").Select 'Error 1004.
End Sub
The simple solution is to Activate the object before you Select within it:
Private Sub NoOneOhOhFour()
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
wb.Activate
wb.Sheets("Sheet1").Range("A1").Select 'No error.
End Sub
Even better is using references and trying to avoid using the Selection and Active* objects entirely.

How to copy the code used in one sheet/tab in a workbook to create a report in another sheet/tab within the same workbook

Let's say, there is a report that has already been created in a sheet in a work book using macros. I want to create another report within the same workbook in another sheet(tab) with the exact same code in VBA which was used to create the report that has already been created. How do i copy and make those codes work in a different sheet to create a similar report?
Any code in the Worksheet itself should use Me to refer to itself - this way, it will work when copied/duplicated
Any other code should take the Worksheet to act on as a Argument, or as Module Level Object:
Option Explicit
Sub CreateReport(TargetSheet As Worksheet)
TargetSheet.Cells(1,1).Value = "Hello"
End Sub
or
Option Explicit
Public TargetSheet AS Worksheet
Sub CreateReport()
If TargetSheet Is Nothing Then Exit Sub 'In case the object has not been set
TargetSheet.Cells(1,1).Value = "Hello"
End Sub
Then you can duplicate a "master" template sheet, and run the macros to target it

Run Time Error '1004': Select method of Range Class failed using ThisWorkbook

During the process of running a script if I manually remove focus from the Workbook containing the macro I get the error quoted. If I don't click on anything it works without issue. Script errors out only when I'm trying to place selection back into A1 from the "Input" sheet. Break point is on following line:
ThisWorkbook.Sheets("Input").Range("A1").Select
If I debug and place focus back on macro Worksheet the script completes without issue. Previous line:
ThisWorkbook.Sheets("Input").Cells.Delete
runs without error so I'm guessing its the range that is falling out of scope but don't quite understand why as it should be defined by the previous scope notations.
Can someone explain why that line is falling out of scope? Shouldn't the ThisWorkbook define fairly explicitly the Workbook that my code is referencing? Any guidance is greatly appreciated.
It doesn't have anything to do with the reference to ThisWorkbook at all. You simply can't Select a Range in an object that isn't active. Consider this code, which exhibits the same error:
Private Sub OneOhOhFour()
'Executing with Book1.xlsm active and Book2.xlsx open.
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
Debug.Print ThisWorkbook.Name
'Outputs 'Book1.xlsm' to Immediate window.
wb.Sheets("Sheet1").Range("A1").Select 'Error 1004
End Sub
Same thing with Worksheets:
Private Sub OneOhOhFourVTwo()
'Starting on anywhere but Sheet2 gives an error.
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1").Select 'Error 1004.
End Sub
The simple solution is to Activate the object before you Select within it:
Private Sub NoOneOhOhFour()
Dim wb As Workbook
Set wb = Application.Workbooks("Book2.xlsx")
wb.Activate
wb.Sheets("Sheet1").Range("A1").Select 'No error.
End Sub
Even better is using references and trying to avoid using the Selection and Active* objects entirely.

Declaring variable workbook / Worksheet vba

I know this might come off as a trivial question, but I can't seem to declare a workbook or a worksheet as a variable in VBA. I have the following code, but I can't figure out what I am doing wrong, it should be straight forward. Normally I don't have any problems declaring variables such as Dim i As Integer etc.
sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheet("name")
wb.ws.Select
End Sub
When I run the above code, I receive a type missmatch error.
Use Sheets rather than Sheet and activate them sequentially:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
If the worksheet you want to retrieve exists at compile-time in ThisWorkbook (i.e. the workbook that contains the VBA code you're looking at), then the simplest and most consistently reliable way to refer to that Worksheet object is to use its code name:
Debug.Print Sheet1.Range("A1").Value
You can set the code name to anything you need (as long as it's a valid VBA identifier), independently of its "tab name" (which the user can modify at any time), by changing the (Name) property in the Properties toolwindow (F4):
The Name property refers to the "tab name" that the user can change on a whim; the (Name) property refers to the code name of the worksheet, and the user can't change it without accessing the Visual Basic Editor.
VBA uses this code name to automatically declare a global-scope Worksheet object variable that your code gets to use anywhere to refer to that sheet, for free.
In other words, if the sheet exists in ThisWorkbook at compile-time, there's never a need to declare a variable for it - the variable is already there!
If the worksheet is created at run-time (inside ThisWorkbook or not), then you need to declare & assign a Worksheet variable for it.
Use the Worksheets property of a Workbook object to retrieve it:
Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)
Dim ws As Worksheet
Set ws = wb.Worksheets(nameOrIndex)
Important notes...
Both the name and index of a worksheet can easily be modified by the user (accidentally or not), unless workbook structure is protected. If workbook isn't protected, you simply cannot assume that the name or index alone will give you the specific worksheet you're after - it's always a good idea to validate the format of the sheet (e.g. verify that cell A1 contains some specific text, or that there's a table with a specific name, that contains some specific column headings).
Using the Sheets collection contains Worksheet objects, but can also contain Chart instances, and a half-dozen more legacy sheet types that are not worksheets. Assigning a Worksheet reference from whatever Sheets(nameOrIndex) returns, risks throwing a type mismatch run-time error for that reason.
Not qualifying the Worksheets collection is an implicit ActiveWorkbook reference - meaning the Worksheets collection is pulling from whatever workbook is active at the moment the instruction is executing. Such implicit references make the code frail and bug-prone, especially if the user can navigate and interact with the Excel UI while code is running.
Unless you mean to activate a specific sheet, you never need to call ws.Activate in order to do 99% of what you want to do with a worksheet. Just use your ws variable instead.
Third solution:
I would set ws to a sheet of workbook wb as the use of Sheet("name") always refers to the active workbook, which might change as your code develops.
sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
'be aware as this might produce an error, if Shet "name" does not exist
Set ws = wb.Sheets("name")
' if wb is other than the active workbook
wb.activate
ws.Select
End Sub
Just coming across the same problem.
What you need to do is to declare ws as Object
Also it should be:
Set ws = wb.Sheets("Sheet1")
And should not be:
Set ws = Sheet("Sheet1")
The code below are working to me.
sub kl()
Dim wb As Workbook
Dim ws As Object
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
MsgBox ws.Name
End Sub
Try changing the name of the variable as sometimes it clashes with other modules/subs
Dim Workbk As Workbook
Dim Worksh As Worksheet
But also, try
Set ws = wb.Sheets("name")
I can't remember if it works with Sheet
to your surprise, you do need to declare variable for workbook and worksheet in excel 2007 or later version. Just add single line expression.
Sub kl()
Set ws = ThisWorkbook.Sheets("name")
ws.select
End Sub
Remove everything else and enjoy.
But why to select a sheet? selection of sheets is now old fashioned for calculation and manipulation.
Just add formula like this
Sub kl()
Set ws = ThisWorkbook.Sheets("name")
ws.range("cell reference").formula = "your formula"
'OR in case you are using copy paste formula, just use 'insert or formula method instead of ActiveSheet.paste e.g.:
ws.range("your cell").formula
'or
ws.colums("your col: one col e.g. "A:A").insert
'if you need to clear the previous value, just add the following above insert line
ws.columns("your column").delete
End Sub
I had the same issue. I used Worksheet instead of Worksheets and it was resolved. Not sure what the difference is between them.
Dim ws as Object
Set ws = Worksheets("name")
when declaring the worksheet as worksheet instead of an ojbect I had issues working with OptionButtons (Active X) in this worksheet (I guess the same will be with any Active-X element. When declared as object everything works fine.
Lots of answers above! here is my take:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set ws = Sheets("name")
Set wb = ThisWorkbook
With ws
.Select
End With
End Sub
your first (perhaps accidental) mistake as we have all mentioned is "Sheet"... should be "Sheets"
The with block is useful because if you set wb to anything other than the current workbook, it will ececute properly

Resources