Attempting to run code on all Excel worksheets

I am trying to run this code on all sheets that I have in a single excel file, but this does not work. It only merges cells on the first sheet. Here is my code:

Sub MergeColumns()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
    Select Case ws.Name
    Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
   ws.Range("H1:S1").Select
            Case Else
    Selection.Merge
        With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
    End With
    End Select
    Next ws
End Sub

I would appreciate that you relate to the same thing.

+2
source share
2 answers

Is that what you are trying?

Option Explicit

Sub MergeColumns()
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        Select Case ws.Name
        Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
            With ws.Range("H1:S1")
                .Merge
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlBottom
            End With
        End Select
    Next ws
End Sub

or if you want to ignore Sheet1 on Sheet4 try this

Option Explicit

Sub MergeColumns()
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        Select Case ws.Name
        Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
        Case Else
            With ws.Range("H1:S1")
                .Merge
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlBottom
            End With
        End Select
    Next ws
End Sub
+3
source

If you want to run the same operation for ALL sheets (which is correct according to my understanding), then why do you need a case with a switch?

you can simply write:

Option Explicit
Sub MergeColumns()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
            With ws.Range("H1:S1")
                .Merge
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlBottom
            End With
    Next ws
End Sub
0
source

Source: https://habr.com/ru/post/1693405/


All Articles