无法关闭打开的工作簿对象

时间:2016-02-25 14:28:41

标签: excel vba excel-vba macros

我有一个宏打开带有测试数据的Excel文件,对数据执行一些简单的格式化,然后将数据保存为新文件(保持最初打开的文件不变)。我得到了一切工作,直到最后一行,我试图关闭我最初打开的工作簿。在尝试关闭原始工作簿之前有一些代码,它将不同的工作簿变量设置为第一个,然后打开并关闭它?我对代码的作用感到有点困惑,但它关闭了用户刚刚保存的新文件,并保留了在开头打开的原始数据文件。这是我的代码如下;当有人保存并关闭工作簿时,有人可以更好地解释发生了什么吗?

Sub Main()
'
'

'
'Define variables
Dim wBook As Workbook
Dim sBook As String
Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As String
Dim NewFileType As String
Dim NewFile As String

'Get workbook filepath
sBook = Application.GetOpenFilename()

If sBook = "False" Then
    End
End If

'Open Workbook
Set wBook = Workbooks.Open(sBook)

'Unrelated formatting occurs

'Save workbook as new file
Application.ScreenUpdating = False    ' Prevents screen refreshing.

CurrentFile = wBook.FullName

NewFileType = "Excel Files 2007 (*.xlsx), *.xlsx,"

NewFile = Application.GetSaveAsFilename( _
    InitialFileName:=NewFileName, _
    fileFilter:=NewFileType)

If NewFile <> "" And NewFile <> "False" Then
    wBook.SaveAs Filename:=NewFile, _
        FileFormat:=xlOpenXMLWorkbook, _
        Password:="", _
        WriteResPassword:="", _
        ReadOnlyRecommended:=False, _
        CreateBackup:=False

    Set ActBook = wBook
    Workbooks.Open CurrentFile
    ActBook.Close
End If

Application.ScreenUpdating = True

wBook.Close

End Sub

1 个答案:

答案 0 :(得分:1)

当你.Save随着wBook对象成为&#34;新文件。&#34;你可以关闭它并保持良好状态。如果要创建一个保持原始对象不变的新对象,则可以使用Workbook.SaveAsCopy。

那么,您的代码中发生了什么:

wBook.SaveAs 

导致wBook成为&#34;新文件&#34;并且&#34;旧文件自动关闭&#34;

Set ActBook = wBook 

基本上是创建两个&#34;新文件&#34;对象。 然后使用

打开旧文件
Workbooks.Open CurrentFile

然后,

ActBook.Close 

关闭了wBook和ActBook。

wBook.Close 

尝试关闭已关闭的工作簿并抛出错误。 (因为它与ActBook相同。)

我相信你的意图如下:

Sub Main()
'
'

'
'Define variables
Dim wBook As Workbook
Dim sBook As String
Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As String
Dim NewFileType As String
Dim NewFile As String

'Get workbook filepath
sBook = Application.GetOpenFilename()

If sBook = "False" Then
    End
End If

'Open Workbook
Set wBook = Workbooks.Open(sBook)

'Unrelated formatting occurs

'Save workbook as new file
Application.ScreenUpdating = False    ' Prevents screen refreshing.

CurrentFile = wBook.FullName

NewFileType = "Excel Files 2007 (*.xlsx), *.xlsx,"

NewFile = Application.GetSaveAsFilename( _
    InitialFileName:=NewFileName, _
    fileFilter:=NewFileType)

If NewFile <> "" And NewFile <> "False" Then
    wBook.SaveAs Filename:=NewFile, _
        FileFormat:=xlOpenXMLWorkbook, _
        Password:="", _
        WriteResPassword:="", _
        ReadOnlyRecommended:=False, _
        CreateBackup:=False
    ' wBook is now the "new file" at this point and the "old file" has been closed. 
End If

Application.ScreenUpdating = True

wBook.Close ' Close the new file.

End Sub