VBA:打开一个 xls 文件并将其添加到当前工作簿
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3657897/
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
VBA: Open an xls file and add it to the current workbook
提问by Ian
I am having trouble with this one. I have an xls file which contains a single sheet of data. In my main application, a different workbook, I want to open this single sheet xls file and copy the sheet into the current workbook.
我遇到了这个问题。我有一个包含单张数据的 xls 文件。在我的主应用程序中,一个不同的工作簿,我想打开这个单一的工作表 xls 文件并将工作表复制到当前工作簿中。
I can do it if I select the range on the source file to copy but this single file may change so I'd rather come up with a solution that just copies the whole file. This is some of the code i've been working with:
如果我选择要复制的源文件的范围,我可以做到这一点,但是这个单个文件可能会改变,所以我宁愿想出一个只复制整个文件的解决方案。这是我一直在使用的一些代码:
Set src = Workbooks.Open(Filename:="thefile.xlsx")
Range("F4:F67").Copy
ThisWorkbook.Activate
Sheets("Result").Activate
Range("A1").Select
ActiveSheet.Paste
I appreciate any help with this.
我很感激这方面的任何帮助。
Thanks
谢谢
回答by marg
Here is a simple solution that doesn't require .Select or .Activate.
这是一个不需要 .Select 或 .Activate 的简单解决方案。
Sub getSheetFromA()
getSheet "a.xls", 1
End Sub
Sub getSheet(filename As String, sheetNr As Integer)
Dim srcWorkbook As Workbook
Set srcWorkbook = Application.Workbooks.Open(filename)
srcWorkbook.Worksheets(sheetNr).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
srcWorkbook.Close
Set srcWorkbook = Nothing
End Sub
回答by Ian
I found a solution:
我找到了一个解决方案:
Set src = Workbooks.Open(Filename:="file.xlsx")
Cells.Copy
ThisWorkbook.Activate
Sheets("Result").Activate
Range("A1").Select
ActiveSheet.Paste

