繁体   English   中英

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

[英]VBA: How to combine two ranges on different sheets into one, to loop through

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

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命令处停止。

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

现在你掌握了所有范围及其边界......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM