Question

i need to rename all my sheets dynamically based on a range of cell values. This is my VBA codes, it keeps giving me a 'Runtime Error '1004 whenever i run it.

Sub RenameSheets()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Config").Range("A5")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
Sheets("Sheet1").Activate
For Each MyCell In MyRange
ActiveSheet.Name = MyCell.Value 'Error here. it works fine if i rename MyCell.Value to "AnyRandomValue"
Worksheets(ActiveSheet.Index + 1).Select
Next MyCell
End Sub

I cant get my head around it. Why is it giving an error at MyCell.Value? Please help!

Was it helpful?

Solution

The problem I think is activating the sheets your working on by .Select method.
Avoid using select as much as possible. Check out the link.
Your code can be rewritten like below:

Sub RenameSheets() 
Dim MyNames As Variant
MyRange As Range, ws As Worksheet
Dim i As Long

With Sheets("Config")
    Set MyRange = .Range("A5", .Range("A" & _
        .Rows.Count).End(xlUp).Address)
    '~~> pass names to array
    MyNames = Application.Transpose(MyRange)
    i = Lbound(MyNames)
End With

'~~> iterate sheets instead
For Each ws In Worksheets
    If ws.Name <> "Config" Then
        ws.Name = MyNames(i) '~~> retrieve from array
        i = i + 1
    End If
Next ws

End Sub

Is this what you're trying?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top