参考多个工作表中的相同动态范围

时间:2016-09-21 04:19:54

标签: excel vba

我循环创建一个通用范围,我想将其应用于8个工作表(除了值之外是相同的。)

For j = 2 To blockNo
row1 = 3 + (j - 1) * (pronum + 18)
row2 = row1 + pronum - 1
Set rng2 = Union(rng2, Range("Q" & row1 & ":BA" & row2))
Next j

For k = 1 To 8
Sheets(k).Activate
rng2.Copy........

它无法正常工作,因为rng2是特定于工作表的,因此它会从工作表1中复制范围值。

我认为以下可能是一个解决方案,但它并不优雅且会很慢。

For k = 1 To 8
    Sheets(k).Activate
    For j = 2 To blockNo
    row1 = 3 + (j - 1) * (pronum + 18)
    row2 = row1 + pronum - 1
    Set rng2 = Union(rng2, Range("Q" & row1 & ":BA" & row2))
    Next j
    rng2.Copy........

我已尝试过工作表(k).range(rng2.address),但这似乎仅限于一定数量的字符,所以我的范围并不能捕获整个rng2。

还有其他解决方案吗?

1 个答案:

答案 0 :(得分:0)

假设地址太长而无法直接传递给.Range(),我能想到的最好的方法是使用Union手动重新创建范围:

For j = 2 To blockNo
    row1 = 3 + (j - 1) * (pronum + 18)
    row2 = row1 + pronum - 1
    Set rng2 = Union(rng2, Range("Q" & row1 & ":BA" & row2))
Next

Dim sheet As Worksheet
Dim target As Range
For k = 1 To 8
    Set sheet = Sheets(k)
    Set target = sheet.Range(rng2.Cells(1, 1).Address)
    Dim cell as Range
    For Each cell In rng2.Cells
        Set target = Union(sheet.Cells(cell.Row, cell.Column), target)
    Next cell
    sheet.Activate
    rng2.Copy........
Next