在工作表上使用不同的范围,然后在同一文件中的20张纸上重复相同的范围

时间:2016-05-05 12:39:57

标签: excel-vba vba excel

我有一张20张的文件,每张纸上的数据都是相同的位置(所有20张是彼此的镜像副本),只有内容不同。目前我正逐一更新每张纸。我已经列出了下面的3个范围并使用Union进行格式化,但是对于每个单元循环代码都很困难 - 我如何得到它:转到每个工作表上的单元格P6并计算10 * 5;转到单元格T33并计算100/10;转到单元格q49并执行50-5等。或者转到范围P6:T9并计算20 * 10。谢谢

Sub MultipleRange()
    Dim r1, r2, r3, r4, r5, r6, myMultipleRange As Range
    Set r1 = Sheets("Sheet1").Range("P6:T9")
    Set r2 = Sheets("Sheet1").Range("P28:T34")
    Set r3 = Sheets("Sheet1").Range("P55:T55")
    Set r4 = Sheets("Sheet2").Range("P6:T9")
    Set r5 = Sheets("Sheet2").Range("P28:T34")
    Set r6 = Sheets("Sheet2").Range("P55:T55")
    Set myMultipleRange = Union(r1, r2, r3, r4, r5, r6)
    myMultipleRange.Font.Color = vbBlue
End Sub

2 个答案:

答案 0 :(得分:1)

以下代码可以解决问题:

Sub MultipleRange()
    Dim r1 As Range, r2 As Range, r3 As Range
    Dim r4 As Range, r5 As Range, r6 As Range
    Dim myMultipleRange As Range
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        With ws

            Set r1 = .Range("P6:T9")
            Set r2 = .Range("P28:T34")
            Set r3 = .Range("P55:T55")
            Set r4 = .Range("P6:T9")
            Set r5 = .Range("P28:T34")
            Set r6 = .Range("P55:T55")
            Set myMultipleRange = Union(r1, r2, r3, r4, r5, r6)
            myMultipleRange.Font.Color = vbBlue

        End With
    Next ws
End Sub

答案 1 :(得分:1)

我使用了@ user3561813的代码并略微更改了它以符合我认为您的确切需求。

Sub MultipleRange()

    Dim r1 As Range, r2 As Range, r3 As Range

    Dim myMultipleRange As Range
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
'got help from http://stackoverflow.com/questions/20422356/loop-through-excel-sheets
        If (ws.Name <> "Sum") And (ws.Name <> "graphs") And (ws.Name <> "comms") Then

            With ws

                Set r1 = .Range("P6:T9")
                Set r2 = .Range("P28:T34")
                Set r3 = .Range("P55:T55")

                Set myMultipleRange = Union(r1, r2, r3)
                myMultipleRange.Font.Color = vbBlue
                r1 = 10 * 5
                r2 = 100 / 10
                r3 = 50 - 5
            End With
        End If
        Next ws

    End Sub

PS:不确定我是否应该只是编辑他的答案并等待或只是回答我自己以便更快地看到答案。