vba 如何附加或组合范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25422103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append or combine Ranges?
提问by Mir
Im doing an app with Excel VBA and I need to copy some ranges from different Worksheet in a variable.
All the ranges have the same number of columms but different number of rows. I was thinking on making like a matrix. Just append the UsedRange from every Sheet one down the other... but no way
我正在使用 Excel VBA 做一个应用程序,我需要从变量中的不同工作表中复制一些范围。
所有范围的列数相同,但行数不同。我正在考虑制作一个矩阵。只需将每个工作表中的 UsedRange 一个一个地附加到另一个......但没有办法
For i = 1 To wbDataFile.Sheets.Count
Set wsCPDataFile = wbDataFile.Sheets(wbDataFile.Sheets(i).Name)
If Not DataRng Is Nothing Then
Set DataRng= DataRng (Append??)
Else
' the first valid cell becomes rng2
Set DataRng = wsCPDataFile.UsedRange
End If
Next I
Data = DataRng
回答by Jzz
Use Union. Like so:
使用联盟。像这样:
Sub jzz()
Dim rng As Range
Set rng = Range("A1")
Set rng = Union(rng, Range("A2"))
End Sub
回答by izzatd
Excel vba provided built in method for range combination, which are:
Excel vba 提供了内置的范围组合方法,它们是:
In case it is required to duplicate the same range, you need to diy, eg refer to rng5
:
如果需要复制相同的范围,你需要自己动手,例如参考 rng5
:
Sub duplicateRange()
Dim rng1 as Range, rng2 as Range, rng3 as Range, rng4 as Range, rng5 as Range
Set rng1 = Range("A1")
Set rng2 = Range("A1")
Set rng3 = Union(rng1, rng2) ' this will give Range("A1") only
Set rng4 = Intersect(rng1, rng2) ' this will give Range("A1") only
Set rng5 = Range(rng1.Address & "," & rng2.Address) ' this will give Range("A1,A1")
End Sub
Though looks silly, I recently encountered the need to have this duplicated multiple range for plotting purposes. My xValues were referring to the same cell, but at different yValues.
虽然看起来很傻,但我最近遇到了出于绘图目的而需要有这个重复的多个范围的情况。我的 xValues 指的是同一个单元格,但在不同的 yValues。