2

I am trying to run this code on all worksheets that I have in one excel file but this is not working. It only merges cells on 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 your time regarding the same.

Community
  • 1
  • 1
Nupur
  • 347
  • 8
  • 19
  • 36

2 Answers2

3

Is this 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 to Sheet4 then 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
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

If you want to run the same operation for ALL sheets(which is right as per my understanding), then, why do you need switch case?

you can just 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
tumchaaditya
  • 1,267
  • 7
  • 19
  • 49