简体   繁体   English

VBA:打开一个xls文件并将其添加到当前工作簿中

[英]VBA: Open an xls file and add it to the current workbook

I am having trouble with this one. 我对此有麻烦。 I have an xls file which contains a single sheet of data. 我有一个xls文件,其中包含一个数据表。 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文件并将工作表复制到当前工作簿中。

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 谢谢

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

I found a solution: 我找到了解决方案:

Set src = Workbooks.Open(Filename:="file.xlsx")
Cells.Copy

ThisWorkbook.Activate
Sheets("Result").Activate
Range("A1").Select
ActiveSheet.Paste

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM