简体   繁体   中英

Workbook will not close with VBA unless opened manually

I have a workbook that I open with VBA, modify said workbook, and then close said workbook. So far what I have is:

 Sub OpenandModify()
 application.screenupdating = false
 workbooks.open Filename:="FilePath\WkbkName.xlsm"

*Modify Workbook 


Workbooks("WkbkName.xlsm").close SaveChanges:=True
application.screenupdating = true
End Sub()

If I run the macro with the workbook already open, the macro works correctly and closes the workbook mentioned above. However, if the workbook is not already open, then the file remains open after the modification (Note, the modifications take place so I do not think it is an issue with the Workbook.Open). Any ideas?

Thanks in advance.

After playing around more with my workbook. I seem to have found the issue. In the modify code portion, I have another subroutine that adds a worksheet from a workbook different than WkbkName.xlsm. If the sheet already exists it gets added as Sheet(2) and the workbook will not close. If the worksheet does not exist then the workbook opens and modifies correctly and shuts. I still do not understand why it acts like this so if anyone has any ideas it would be greatly appreciated.

For now, I just plan to add a check for duplicate worksheets and exit the sub if it happens.

Some of the problems you've encountered may be due to the code getting confused with which workbook it's working on.

Use a variable to hold a reference to your workbook and use only that throughout the code:

 Sub OpenandModify()

    Dim wrkBk As Workbook

    Application.ScreenUpdating = False
    'Open the workbook and assign it to wrkBk variable.
    Set wrkBk = Workbooks.Open(Filename:="FilePath\WkbkName.xlsm")

    'Modify Workbook
    With wrkBk
        .Worksheets("Sheet1").Range("A1") = "Modified!"
    End With

    wrkBk.Close SaveChanges:=True
    Application.ScreenUpdating = True

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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