How can I set a worksheet object based on a worksheet's codename? - vba

The worksheet name may change. Because of that I want to set the worksheet object based on the worksheet's codename. How can I do this?
My best attempt so far is:
Sub UpdateNameDropdown()
Dim wksName As String
wksName = ThisWorkbook.Sheets(Sheet16).Name
Dim wks As Worksheet
Set wks = Sheets(wksName)
End Sub
But I get a type mismatch error on the row wksName = ThisWorkbook.Sheets.Sheet16.Name

This?
Sub Sample()
Dim wks As Worksheet
Set wks = Sheet16
With wks
Debug.Print .Name
'~~> Do what you want
End With
End Sub

This uses the codename as a String
Sub CodeIt()
Dim CodeName As String
CodeName = "Sheet1"
Dim WS As Worksheet, GetWorksheetFromCodeName As Worksheet
For Each WS In ThisWorkbook.Worksheets
If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodeName = WS
Exit For
End If
Next WS
MsgBox GetWorksheetFromCodeName.Name
End Sub

Thank you Gary's Student. I midified your function to the following:
Function GetWorksheetFromCodename(codeName As String) As Worksheet
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
If StrComp(wks.codeName, codeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodename = wks
Exit For
End If
Next wks
End Function

Related

Worksheet CodeName not assigned

I'm trying to assign the code name of a worksheet to a vriable.
Some times it gets the code name correctly, and sometimes it doesn't, the variable stays null.
Dim sCodeName As String
sCodeName = Worksheets(atar).CodeName
atar is a variable that contains the worksheet name.
When i stop the code running, and coninue in debug mode, it works fine.
What can be the reason?
Worksheets without qualification refers to same as ActiveWorkbook, perhaps you're assuming too much about which workbook is active in some instances.
It is recommended to fully qualify Worksheets. So get a reference to a Workbook object , say wbFoo and then use sCodeName = wbFoo.Worksheets(atar).CodeName
You could try something like the code below to verify that atar does exist in one of the worksheet names in ThisWorkbook.
Option Explicit
Sub GetWorksheetCodeName()
Dim sCodeName As String
Dim atar As String
Dim Sht As Worksheet
'atar = "Sheet3" '<-- for tests only
' loop through all worksheets in ThisWorkbook
For Each Sht In ThisWorkbook.Worksheets
If Sht.Name Like atar Then
sCodeName = Worksheets(atar).CodeName
Exit For
End If
Next Sht
End Sub
CREATE MULTIPLE WORKSHEET BUT SOMETIMES NOT WORK WITH MACRO FROM WORKSHEET ONLY WORK WITH VBA CODE RUN
Sub WSCreate()
Dim WSA As String
Dim WSB As String
Dim WS As Worksheet
WSA = "SheetA"
WSB = "SheetB"
Application.DisplayAlerts = False
On Error Resume Next
'DELETE MULTIPLE WORKSHEETS (IF Already Exist)
Set WS = Nothing
Set WS = Sheets(WSA)
WS.Delete
Set WS = Nothing
Set WS = Sheets(WSB)
WS.Delete
Set WS = Nothing
'CREATE MULTIPLE WORKSHEETS
With Application.ThisWorkbook
.Worksheets.Add.Name = WSA 'WSA = SheetA
.VBProject.VBComponents(Worksheets(WSA).CodeName).Name = WSA
.Worksheets.Add.Name = WSB 'WSB = SheetB
.VBProject.VBComponents(Worksheets(WSB).CodeName).Name = WSB
End With
If Err <> 0 Then Exit Sub
End Sub

Type mismatch error VBA loop through worksheets

I keep getting a type mismatch error and have tried changing the type a few times. I'm just trying to loop through each worksheet and a specified range to see if that word exists in every cell of that range.
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
If ws.Range("C9:G20").Value = "Word" Then
MsgBox (True)
End If
Next ws
End Sub
When you have a range with many columns, it creates an array.
Taking the array into consideration like so:
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
For each col in ws.Range("C9:G20").Cells
if col.Value = "Word" Then
MsgBox (True)
end if
End If
Next ws
End Sub
You can't get the value of ws.Range("C9:G20") and compare it to one string. You've selected multiple cells. If you want to return True when nay one of these cells contains "Word" or when all of them contain "Word" you'll need to iterate over them.
This is an example of how to return whether or not your range contains "Word" anywhere at least once
Function CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Set arrVar = ActiveWorkbook.Worksheets
For Each ws In arrVar
Dim c
For Each c In ws.Range("C9:G20").Cells
If c = "Word" Then
CheckWord = True
Exit Function
End If
Next c
Next ws
End Function
Sub CheckWord()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If Not ws.Range("C9:G20").Find(What:="Word", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) Is Nothing Then MsgBox "Found in " & ws.Name
Next ws
End Sub

Looping through different sheets

I would appreciate your help with the macro I am trying to create.
I have an xls file with a bunch of worksheets, some of which named "1", "2", "3", and so forth. I would like to create a macro that loops only through those 'number-named' worksheets, hence NOT according to the index as in the code below. (Sheet "1" is not the first sheet in the workbook). Before the loop I need to define both the cell range and sheets.
Below is my (wrong) attempt.
Sub Refresh ()
Dim i As Integer
Dim rng As Range
Set rng = Range("A10:TZ180")
For i = 1 To 30
Sheets(i).Activate
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
Next i
End Sub
dim w as worksheet
for each w in activeworkbook.worksheets
if isnumeric(w.name) then
w.range("A10:TZ180").clearcontents
xxx()
end if
next
If the macro "xxx()" requires a selected range you just need to add a select statement. (Borrowing from GSerg)
Dim w As Worksheet
For Each w In ActiveWorkbook.Worksheets
If IsNumeric(w.Name) Then
w.Range("A10:TZ180").ClearContents
w.Range("A10:TZ180").Select
Application.Run macro:="xxx"
End If
Next
To clear up your misunderstanding about assigning a range see the following:
Sub Refresh()
Dim ws As Worksheet
Dim rng As Range
Dim i As Integer
For Each ws In ActiveWorkbook.Worksheets
If IsNumeric(ws.Name) Then
'you must activate the worksheet before selecting a range on it
ws.Activate
'note the qualifier: ws.range()
Set rng = ws.Range("A10:TZ180")
'since the range is on the active sheet, we can select it
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
End If
Next
End Sub
Sub test2()
Dim ws As Worksheet
Dim rg As Range
Dim arrSheets As Variant
arrSheets = Array("Sheet1", "Sheet2", "Sheet3")
Dim x As Long
For x = LBound(arrSheets) To UBound(arrSheets)
Set ws = Worksheets(arrSheets(x))
ws.Activate
'...
Next
End Sub
Sub test3()
Dim ws As Worksheet
Dim x As Long
For x = 1 To 20
Set ws = Worksheets(CStr(x))
ws.Activate
'...
Next
End Sub
try this
Sub main()
Dim shtNames As Variant, shtName As Variant
shtNames = Array(1, 2, 3, 4) '<== put your actual sheets "number name"
For Each shtName In shtNames
With Worksheets(CStr(shtName))
.Range("A10:TZ180").ClearContents
.Range("A10:TZ180").Select
Application.Run macro:="MacroToRun"
End With
Next shtName
End Sub
Sub MacroToRun()
MsgBox "hello from cells '" & Selection.Address & "' in sheet '" & ActiveCell.Parent.Name & "'"
End Sub

Method Paste failed, but code looks simple (and have worked before)

What is wrong with this code?:
Private Sub Copy_Images()
Dim wks, wks2 As Worksheet
Set wks = Sheets("export")
Set wks2 = Sheets("HomePage")
wks2.Activate
wks2.Shapes("picture").Copy
wks.Activate
wks.Paste Range("A1")
End Sub
Error: Method 'Paste' of object '_Worksheet' failed - 1004
Try this:
Private Sub Copy_Images()
Dim wks as worksheet, wks2 As Worksheet
Set wks = Sheets("export")
Set wks2 = Sheets("HomePage")
wks2.Shapes("picture").Copy
wks.range("A1").Paste
End Sub
Try below code
Private Sub Copy_Images()
Dim wks As Worksheet
Dim wks2 As Worksheet
Set wks = Sheets("export")
Set wks2 = Sheets("HomePage")
wks2.Activate
wks2.Shapes("picture").Copy
wks.Activate
Range("A1").Select
ActiveSheet.Paste
End Sub

Excel VBA loop & cell value match

What I am trying to do seems basic enough, however I don't know where I am going wrong with the code.
I want to run the selected cell through a loop of the worksheets and select the worksheet that matches the selected cell located in cell B1.
Dim SelectedCell as Range
Dim ws As Worksheet
Set SelectedCell = Range(ActiveCell.Address)
For Each ws In ActiveWorkbook.Worksheets
If ws.Range("B1").Value = SelectedCell.Value Then
ActiveSheet.Select
End If
Next ws
End Sub
Thanks in advance for all the help!
Try instead
Dim ws As Worksheet
SelectedCell = ActiveCell
For Each ws In ActiveWorkbook.Worksheets
If ws.cells(1,2) = SelectedCell Then
ws.Select
End If
Next ws
End Sub
Select cell run macro will select the sheet name that matches the selected cell. (Case sensitive)
Dim SelectCell As String
Dim ws As Worksheet
SelectCell = ActiveCell.Value2
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = SelectCell Then
ws.Select
End ID
Next ws