vba 将表格复制到另一个工作表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31702885/
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
Copy tables to another worksheet
提问by Alex664
I have 2 tables, "Table1" and "Table2" in Worksheet(1).
我在 Worksheet(1) 中有 2 个表,“Table1”和“Table2”。
I would like to copy these tables to another worksheet(2) where the top left corner of Table1 is in the new worksheet at cell "A1" and the Top left corner cell of Table2 is in the new worksheet at cell "O1."
我想将这些表格复制到另一个工作表 (2),其中 Table1 的左上角位于单元格“A1”的新工作表中,Table2 的左上角单元格位于单元格“O1”的新工作表中。
Unless the ActiveCell is A1 in Sheet2, the tables won't copy and paste correctly. Am I not activating a sheet correctly?
除非 ActiveCell 是 Sheet2 中的 A1,否则表格将无法正确复制和粘贴。我没有正确激活工作表吗?
Sub CopyTables()
Worksheets(2).Activate 'must be on ExHouStorm or Worksheet(1)
Worksheets(1).ListObjects("Table1").Range.Copy
Worksheets(2).Paste
Worksheets(1).ListObjects("Table2").Range.Copy
Worksheets(2).Range("O1").Select
Worksheets(2).Paste
End Sub
This seems pretty simple as it partially works but I think I have a syntax mistake.
这看起来很简单,因为它部分有效,但我认为我有一个语法错误。
回答by
You should be able to copy directly by providing the destination.
您应该能够通过提供目的地直接复制。
Sub CopyTables()
Worksheets(1).ListObjects("Table1").Range.Copy _
Destination:=Worksheets(2).Range("A1")
Worksheets(1).ListObjects("Table2").Range.Copy _
Destination:=Worksheets(2).Range("O1")
End Sub
By directly and explicitly addressing the objects and their destinations, you can avoid .Activateand .Selectaltogether.
通过直接和明确解决的对象和他们的目的地,你能避免.Activate和.Select完全。
See How to avoid using Select in Excel VBA macrosfor more methods on getting away from relying on select and activate to accomplish your goals.
有关摆脱依赖选择和激活来实现目标的更多方法,请参阅如何避免在 Excel VBA 宏中使用选择。
回答by Ankush agarwal
Another method, simpler and shorter:
另一种更简单、更短的方法:
Range("Table1[#All]").copy Range("L1")

