Question

I am trying to build quite a complex excel macro based on dynamic data. My first stumbling block is that i am struggling to get a button-triggered Excel macro to take name of each tab after the current one and insert its name every third column of the current sheet

I have:

    Sub Macro1()
    On Error Resume Next
    For Each s In ActiveWorkbook.Worksheets
    Sheet2.Range("A1:ZZ1").Value = s.Name
    Next s
    End Sub

This really does not work well, as it simply seems to enter the name of the last sheet all the way between A1 and ZZ1! what am I doing wrong?

Was it helpful?

Solution

This will put the names of worksheets in the tabs to the right of the Activesheet in every 3rd column of row 1 of the Activeshseet:

Sub Macro1()
Dim i As Long

With ThisWorkbook
    'exit if Activesheet is the last tab
    If .ActiveSheet.Index + 1 > .Worksheets.Count Then
        Exit Sub
    End If
    For i = .ActiveSheet.Index + 1 To .Worksheets.Count
        .ActiveSheet.Cells(1, (i - .ActiveSheet.Index) + (((i - .ActiveSheet.Index) - 1) * 2)) = .Worksheets(i).Name
    Next i
End With
End Sub

Please note that it's a bad idea to useOn Error Resume Next in the general manner that you did in your original code. It can mistakenly mask other errors that you don't expect. It should just be used to catch errors that you do expect.

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