VBA:如何将不同工作表上的两个范围合并为一个,以便循环

时间:2014-09-12 06:18:21

标签: excel-vba vba excel

尝试读取两个相等宽度但不同长度的范围,每个范围在不同的工作表上,到另一个范围,我需要按特定顺序循环组合数据。

Set wRIL = Worksheets("INS")
Set rRIL = wRIL.Range("L2")
Set rRIL = rRIL.CurrentRegion
Set rRIL = rRIL.Offset(1, 0).Resize(rRIL.Rows.Count - 1, rRIL.Columns.Count)

Set wROL = Worksheets("OUTS")
Set rROL = wROL.Range("N2")
Set rROL = rROL.CurrentRegion
Set rROL = rROL.Offset(1, 0).Resize(rROL.Rows.Count - 1, rROL.Columns.Count)

Set rRILROL = Union(rRIL, rROL)  

希望得到一个大小范围rROL.Rows.Count + rRIL.Rows.Count long和rROL.Columns.Count宽。 此代码在Union命令处停止。

1 个答案:

答案 0 :(得分:2)

Union函数不能跨越多个工作表(因为任何范围对象都包含在单个Worksheet对象中)。如果要在一个循环中处理不同工作表上的多个范围,则需要考虑不同的策略,例如

Sub test()
Dim AllAreas(2) As Range, Idx As Integer, MyCell As Range, TargetRange As Range

    Set AllAreas(0) = Worksheets("Sheet1").[C4]
    Set AllAreas(1) = Worksheets("Sheet2").[D5]
    Set AllAreas(2) = Worksheets("Sheet3").[E6]
    Set TargetRange = Worksheets("Sheet4").[A1]

    For Idx = 0 To 2
        For Each MyCell In AllAreas(Idx).Cells
            MyCell = "co-cooo!"
            ' combine in targetrange - each cell of any source range is put at same position
            ' in sheet 4 ... mind the precedence ... highest sheet highest prio
            TargetRange(MyCell.Row, MyCell.Column) = MyCell
        Next MyCell
    Next Idx
End Sub

您可以通过范围数组中所有范围的最小值和最大值.Row以及.Column找到所有范围的叠加层,因此,如果您有一组复杂的规则来聚合部分重叠范围,从找到最小和最大角落开始,遍历目标范围的所有单元格并询问:区域0,1,2中是否有值......如果是,则决定哪一个优先。

为了让事情更加优雅,你可以建立......

Type RngDef
    Rng As Range
    MinCol As Integer
    MaxCol As Integer
    MinRow As Integer
    MaxRow As Integer
End Type

Sub test2()

Dim AllAreas(2) As RngDef, Idx As Integer, MyCell As Range, TargetRange As Range

    Set AllAreas(0).Rng = Worksheets("Sheet1").[C4]
    Set AllAreas(1).Rng = Worksheets("Sheet2").[D5]
    Set AllAreas(2).Rng = Worksheets("Sheet3").[E6]

    For Idx = 0 To 2
        AllAreas(Idx).MinCol = AllAreas(Idx).Rng(1, 1).Column
        AllAreas(Idx).MinRow = AllAreas(Idx).Rng(1, 1).Row
        AllAreas(Idx).MaxCol = AllAreas(Idx).MinCol + AllAreas(Idx).Rng.Columns.Count - 1
        AllAreas(Idx).MaxRow = AllAreas(Idx).MinRow + AllAreas(Idx).Rng.Rows.Count - 1
    Next Idx

    Set TargetRange = Worksheets("Sheet4").[A1]


End Sub

现在你手边有所有范围及其边界......