gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:09:34 25 4
gpt4 key购买 nike

尝试将两个宽度相等但长度不同的范围(每个范围在不同的纸张上)读入另一个范围,我需要以特定顺序循环遍历组合数据。

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

现在您已经掌握了所有范围及其边界...

关于excel - VBA:如何将不同工作表上的两个范围合并为一个,循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25801941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com