Excel在复制/粘贴数据宏之后保持打开数据源工作簿

时间:2017-11-08 23:04:39

标签: excel vba excel-vba

我对VBA非常非常新。 我试图通过宏从8个动态“单个”工作簿自动复制数据,粘贴到一个主工作簿中,所有工作簿都分层在8个选项​​卡上,因为各个团队成员将不断更新这些单独的书籍。

我有下面的宏运行良好但是excel之后会使数据源工作簿保持打开状态,这样就无法使用8个单独的文件。

我可以添加哪些代码告诉excel在运行micro后自动关闭数据源文件?添加“工作簿(”C:\ Users \ MIRAR \ Desktop \ AD HOC \ DEMO FILE - WIP \ SHARNY.xlsx“)。在End sub不工作之前关闭”代码末尾并发出错误9。

以下代码是从1个选项卡上的8个工作簿中的1个复制过去的数据。

非常感谢!

Sub CopyingRange()
Workbooks.Open "C:\Users\MIRAR\Desktop\AD HOC\DEMO FILE - WIP\SHARNY.xlsx"

Dim CopyFromBook As Workbook
Dim CopyToWbk As Workbook
Dim ShToCopy As Worksheet

Set CopyFromBook = Workbooks("SHARNY.xlsx")
Set ShToCopy = CopyFromBook.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("Consolidated Tracker File.xlsx")

Workbooks("C:\Users\MIRAR\Desktop\AD HOC\DEMO FILE - WIP\SHARNY.xlsx").Close 

End Sub

2 个答案:

答案 0 :(得分:2)

简短回答是:

Workbooks("SHARNY.xlsx").Close

更好的答案是使用直接指向工作簿的变量:

Sub CopyingRange()
    Dim CopyFromBook As Workbook
    Dim CopyToWbk As Workbook
    Dim ShToCopy As Worksheet

    Set CopyFromBook = Workbooks.Open("C:\Users\MIRAR\Desktop\AD HOC\DEMO FILE - WIP\SHARNY.xlsx")
    Set ShToCopy = CopyFromBook.Worksheets("Sheet1")
    Set CopyToWbk = Workbooks("Consolidated Tracker File.xlsx")

    CopyFromBook.Close
End Sub

答案 1 :(得分:0)

将其分配给工作簿变量并使用它来关闭(或任何其他操作)。

Sub CopyingRange()

Dim CopyFromBook As Workbook
Dim CopyToWbk As Workbook
Dim ShToCopy As Worksheet

Set CopyFromBook = Workbooks.Open("C:\Users\MIRAR\Desktop\AD HOC\DEMO FILE - WIP\SHARNY.xlsx")
Set ShToCopy = CopyFromBook.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("Consolidated Tracker File.xlsx")

CopyFromBook.Close

End Sub