使用 VBA 复制多个范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12465368/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:01:53  来源:igfitidea点击:

Copy multiple ranges with VBA

excel-vbacopyvbaexcel

提问by CaptainProg

I am trying to copy multiple ranges using Excel VBA. I understand that in order to select multiple ranges, syntax similar to that below is used:

我正在尝试使用 Excel VBA 复制多个范围。我知道为了选择多个范围,使用了类似于下面的语法:

Range("A1:B4000, F1:F4000").Select

This works fine in selectingthe appropriate range. However, the following:

这在选择适当的范围时效果很好。但是,以下内容:

Range("A1:B4000, F1:F4000").Copy

...only copies the A1:B4000 range. This is the first problem I am facing.

...仅复制 A1:B4000 范围。这是我面临的第一个问题。

Secondly, I would like to dynamically copy the data to the bottom row, which is not necessarily row #4000. If selecting a single range, the syntax is as follows:

其次,我想将数据动态复制到底行,不一定是行#4000。如果选择单个范围,则语法如下:

Range("A1", Range("B1").End(xlDown)).Copy

The above code successfully copies everything from A1 to the bottom of the B column. I can't find any material on the net explaining how to do this for multiple selections.

上面的代码成功地将所有内容从 A1 复制到 B 列的底部。我在网上找不到任何材料来解释如何为多个选择执行此操作。

What I'm essentially trying to do is copy A1:B(bottom) and F1:F(bottom), but the above two issues are stopping me. I assume this is a syntax issue..?

我基本上想要做的是复制 A1:B(bottom) 和 F1:F(bottom),但上述两个问题阻止了我。我认为这是一个语法问题..?

采纳答案by CaptainProg

@Scott Holtzman provided the solution in a comment:

@Scott Holtzman 在评论中提供了解决方案:

I would just adjust the following, since the OP asked for dynamic range names, Set range1 = Range("A1:B" & Range("B" & Rows.Count).End(xlUp).Row) to get the real last cell in column B. Do the same for column F as well

我只会调整以下内容,因为 OP 要求提供动态范围名称, Set range1 = Range("A1:B" & Range("B" & Rows.Count).End(xlUp).Row) 以获得真正的最后一个B 列中的单元格。 F 列也执行相同操作

回答by MrB

Use the "Union" method.

使用“联合”方法。

Dim range1 as Range, range2 as Range, multipleRangeAs Range    
Set range1 = Sheets("Sheet1").Range("A1:B4000")    
Set range2 = Sheets("Sheet1").Range("F1:F4000")    
Set multipleRange= Union(range1, range2)

Then you can mess around with mutipleRange as per normal.

然后你可以像往常一样使用 mutipleRange 。