在多个工作表中应用范围修改

时间:2018-02-22 11:14:34

标签: excel vba excel-vba

我有一张12张工作簿(每个月的缩写名称)加上两张额外的支持表。我想创建一个宏,我可以在其中定义许多不同的范围(在下面的示例中,有5个范围),将它们分组在一个数组中,并在所有月度工作表上逐个合并这些范围。 我遇到了以下代码(它运行没有错误,显然贯穿了我要求的所有工作表) - 但只在第一个工作表(“Jan”)上应用转换而在其他工作表上什么都不做?你能帮我找一下我的错误吗?在此先感谢大家!

Sub layout()

Dim rng1, rng2, rng3, rng4, rng5 As Range

Set rng1 = Range("A2:C3")
Set rng2 = Range("A4:A5")
Set rng3 = Range("B4:B5")
Set rng4 = Range("C4:C5")
Set rng5 = Range("D2:D5")

Dim arr As Variant
arr = Array(rng1, rng2, rng3, rng4, rng5)

Dim wb As Workbook
Set wb = Application.Workbooks("Book1")

Dim ws As Worksheet
Dim i As Integer

For Each ws In wb.Sheets
    Select Case ws.name
    Case Is = "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        For i = 0 To 4
        ws.Activate
        arr(i).Merge
        Next
    End Select
Next ws

End Sub

2 个答案:

答案 0 :(得分:3)

我不知道这两个额外支持表的名称,让我们只调用它们SupoortSheet1和Supportsheet 2.使用Select case在这两种情况下什么也不做,以及任何其他情况,你合并:

For Each ws In wb.Sheets
    Select Case ws.Name
        Case "SupportSheet1"
            'do nothing
        Case "SupportSheet2"
            'do nothing
        Case Else
            'it's a month sheet. We merge
            For i = 0 To 4
                ws.Activate
                arr(i).Merge
            Next
    End Select
Next ws

关于Case Else的更多信息(有时非常有用),read here

答案 1 :(得分:1)

您的Case语句稍有格式错误并激活工作表以继承活动工作表,因为默认父工作表应该在循环之外。

然而主要问题是您正在设置范围对象。更改活动工作表不会重写这些范围对象的父工作表。尽管更改了活动工作表,仍将保留设置的父工作表。

解决方案是对地址字符串进行排列并动态构建范围。

Option Explicit

Sub layout()
    Dim arr As Variant, wb As Workbook, ws As Worksheet, i As Integer
    arr = Array("A2:C3", "A4:A5", "B4:B5", "C4:C5", "D2:D5")

    Set wb = Application.Workbooks("Book1")

    For Each ws In wb.Worksheets
        Select Case ws.Name
            Case "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                For i = 0 To 4
                    ws.Range(arr(i)).Merge
                Next
        End Select
    Next ws

End Sub