2

我正在尝试在一个 Excel 文件中的所有工作表上运行此代码,但这不起作用。它只合并第一张纸上的单元格。这是我的代码:

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

我会很感激你的时间。

4

2 回答 2

3

这是你正在尝试的吗?

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

或者如果你想忽略 Sheet1 到 Sheet4 然后试试这个

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
于 2012-04-23T21:15:38.280 回答
0

如果您想对所有工作表运行相同的操作(根据我的理解,这是正确的),那么,为什么需要 switch case?

你可以写:

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
于 2012-04-27T05:00:54.507 回答