How to set a sheet by codename to pass to a UDF? - excel

I want to set a sheet by codename.
It seems to break a lot of functions etc.
This problem with codenames is not clearly defined in any of the discussions I've come across.
This doesn't work.
Dim x as Worksheet
Set x = SheetCodeName1
I need to pass that variable to a function, where the function's variable is Dim'd As WorkSheet.
Is there not a work around like Set x = Worksheet(SheetCodeName(Name))?

I have a worksheet with a Name, "Sheet1" - this Name is what shows on the tabs at the bottom of my workbook. In the VBA IDE, I can see the Name in brackets next to the CodeName. Below, I've renamed the CodeName to ws1:
Now in the code I can refer to it directly using the codename like this:
Sub Example1()
ws1.Range("A1").Value2 = "Hello, world!"
End Sub
I can dimension and set a worksheet variable using the codename no problem:
Sub Example2()
Dim ws As Worksheet
Set ws = ws1
ws.Range("A1").Value2 = "Goodbye, world!"
End Sub
It passes as a function or sub parameter no problem:
Sub Example3()
Dim ws As Worksheet
Set ws = ws1
myNewSub ws
End Sub
Sub myNewSub(sh As Worksheet)
sh.Range("A1").Value2 = "Hello again, world!"
End Sub
I can also set a worksheet using it's Name but have to refer first to the workbook's worksheets collection:
Sub Example4()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Range("A1").Value2 = "That's enough, world!"
End Sub

Related

Sum values from one Worksheet in another Worksheet

I am trying to sum values from my original worksheet in specific cells in my newly created worksheet, which has a template to fill out.
When I used macro recorder, it references the worksheet name, which would not be useful as the worksheet name changes depending on which worksheet I am working in when I run the code.
So I tried changing the worksheet name to a variable "XCXX".
The first argument works so I thought everything was okay, however, on the second argument, it keeps trying to open a file, when it should simply go back to XCXX and pull the values.
Is it a problem with my activesheet changing?
Sub AddWorkbooks()
Dim ChangeOrder As Range
Dim XCXX As Worksheet
Dim CoForm As Worksheet
Set XCXX = ActiveSheet
Set CoForm = Worksheets("+CO Form+")
'Set wbNew = Workbooks.Add
CoForm.Copy After:=Sheets(ActiveSheet.Index)
With CoForm
Range("A6:D6").Select
ActiveCell.FormulaR1C1 = XCXX.Range("D2").Value
Range("AD81").Select
ActiveCell.FormulaR1C1 = "='XCXX'!R[-64]C[-24]+'XCXX'!R[-64]C[-23]"
End With
End Sub
This should be close:
Sub AddWorkbooks()
Dim ChangeOrder As Range
Dim XCXX As Worksheet, wb As Workbook
Dim CoForm As Worksheet, CoFormCopy As Worksheet
Set wb = ActiveWorkbook
Set XCXX = ActiveSheet
Set CoForm = wb.Worksheets("+CO Form+")
CoForm.Copy After:=XCXX
Set CoFormCopy = XCXX.Next 'the copy of "+CO Form+"
With CoFormCopy 'assuming you want to work with the copy?
.Range("A6:D6").Value = XCXX.Range("D2").Value
.Range("AD81").FormulaR1C1 = _
Replace("='<nm>'!R[-64]C[-24]+'<nm>'!R[-64]C[-23]", "<nm>", XCXX.Name)
End With
End Sub
Note when using With you need to use a period to link (eg) Range() with the object used in the With statement, otherwise it defaults to the active sheet.
Also generally there's no need to select a range to do something with it.

Do you need to pass both the workbook and worksheet to sub/function

If you are going to be just working with a single worksheet in your function or sub and you pass the worksheet, do you also need to pass the workbook, or does that come along with worksheet that was passed?
Option 1
Sub option1 (byref wb as workbook, byref ws as worksheet)
wb.ws.range("A1") = 8
end sub
Option 2
sub option2(byref ws as worksheet)
ws.range("A1") = 8
end sub
in option 2 is there any danger of of opening a worksheet with the same name in a different workbook then then the one you passed the worksheet from?
The worksheetobject always has a workbook as a parent. So as long as you make sure you're calling the right worksheet when passing it on, you should be fine. So something like this should always work:
dim ws as Worksheet
set ws = ThisWorkbook.Sheets("Sheet1")
call option2(ws)

How can I get worksheet code name to activate a specific worksheet?

I have a worksheet with the "tab" name of "Rpt_Group". I also renamed its code name to shData. When I use VBA to activate the worksheet using "Rpt_Group" it runs fine. But when I use the code name I get an error message
"subscript out of range.
This works: WBA.Worksheets("Rpt_Group").Activate
This does not work: WBA.Worksheets("shData").Activate
This does not work: WBA.shData.Activate
Dim WBA As Workbook
'Open the desired workbook
Set WBA = Workbooks.Open(Filename:="path & file name")
'Activate the desired worksheet
WBA.Worksheets("Rpt_Group").Activate 'this works
This does not work: WBA.Worksheets("shData").Activate
This does not work: WBA.shData.Activate
Here's one solution:
Sub tester()
Dim WBA As Workbook
Set WBA = Workbooks("Book1")
WorksheetByCodeName(WBA, "codeNameHere").Activate
End Sub
'Get a worksheet with matching codeName (or Nothing if no match)
' from a workbook wb
Function WorksheetByCodeName(wb As Workbook, codeName As String)
Dim ws As Worksheet, rv As Worksheet
For Each ws In wb.Worksheets
If ws.codeName = codeName Then
Set rv = ws
Exit For
End If
Next ws
Set WorksheetByCodeName = rv
End Function
Probably want to check the return value before trying to do anything with it.

Connect dim ws As Worksheet with me.textbox

it is possible to connect worksheet like so? const ws = me.textbox
I would like to make a drop down list with possibility to chose worksheets in my user form.
I know that method won't work i pasted it below.
Is there any other possibility to make it work?
I use select casebut it means that i write my whole code X times
Sub Populate()
Dim ws As Worksheet
Set ws = me.ChoseSheet
First assign text box value to string and then pass it to set
strSheetName = Me.ChoseSheet
Set ws = ThisWorkbook.Worksheets(strSheetName)
You could use a For each loop to populate a ComboBox on a UserForm
For example:
Public Sub UserForm_Initialize()
Dim ws as WorkSheet
For each ws in ActiveWorkbook.Worksheets
Combobox1.AddItem(ws.Name)
next ws
End sub

Finding Part of a Sheet Name

I want to update a worksheet. The name of the worksheet changes with the date.
As an example the worksheet would have been named
"Hello World 6.13" on Monday
"Hello World 6.17" today
How can I looks for the sheet name that starts with "Hello World" and ignores the date code?
They way I would go about this would be to loop through the sheets in the active workbook and make the comparison, and when the correct sheet "Hello World x.xx" is found set it as a reference, and use this reference to run any further code.
Let searchTerm = "Hello World"
For Each ws In ActiveWorkbook.Sheets
If Left(ws.Name, Len(searchTerm)) = searchTerm Then
Set hwSheet = ws
Exit For
End If
Next ws
'do some code eg:
With hwSheet
.Range("A1").Value = "Hi"
End With
So the spreadsheet you want to capture is always the same sheet, in the same workbook? If I've got this right, you can use the codename of the worksheet in the client's workbook, such as Sheet1 instead of the worksheet name.
Dim wb As Workbook, ws as Worksheet
Set wb = Workbooks("Client.xls")
wb.Activate
Set ws = Sheet1
You would have to activate the appropriate workbook before using the sheet codename. To be sure this works, it would be prudent to change the client's sheet codename to something unique (if it isn't already) if that is within your purview.
Posted below is a version of Oliver's code that addresses working with the found sheet inside the loop, rather than the last found match.
A couple of other minor tweaks
The string version of Left$ is quicker than the variant Left
if you set an object in a loop, should set it back to nothing before retesting (which is not evident in the code below as I used the existing ws)
code
Sub Updated()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
If Left$(ws.Name, 11) = "Hello World" Then
With ws
'do something
End With
End If
Next ws
End Sub
Another option to return all partial sheet matches without a loop is in Adding Sheet Names to Array in Excel VBA
While I liked #Carrosives answer (https://stackoverflow.com/a/37882970/5079799). I decided to functionalize it. In that regard, I didn't want to use LEFT or RIGHT but InSTR.
Here is what I got:
Public Function FindWorksheet(PartOfWSName As String) As Worksheet
For Each ws In ActiveWorkbook.Sheets
If InStr(ws.Name, PartOfWSName) > 0 Then
Debug.Print ws.Name
Set FindWorksheet = ws
Exit For
End If
Next ws
End Function
Sub TestingSpot_Sub()
Dim PartOfWSName As String
PartOfWSName = "Testz"
Dim ws As Worksheet
Set ws = FindWorksheet(PartOfWSName)
ws.Activate
End Sub
This should be enough:
Sub CallTheRealThing()
Call SelectSheets("Sheet")
End Sub
Sub SelectSheets(NameNeededinSheet As String, Optional Looked_Workbook As Workbook)
Dim WorkSheetProject As Worksheet
If Looked_Workbook Is Nothing Then Set Looked_Workbook = ThisWorkbook
For Each WorkSheetProject In Looked_Workbook.Worksheets
If InStr(WorkSheetProject.Name, NameNeededinSheet) Then: WorkSheetProject.Select: Exit Sub
Next WorkSheetProject
End Sub
You may change it to a Function instead of sub to know if it could select the sheet or not

Resources