Jump to content

Close an in use file


Recommended Posts

I want to close an in use excel file with below code but fail with error. Please help

>"C:\Program Files\AutoIt3\SciTE\..\autoit3.exe" /ErrorStdOut "C:\w5\Auto\t4.au3"

C:\w5\Auto\t4.au3 (6) : ==> The requested action with this object has failed.:

For $element In $oExcel.Application.Workbooks

For $element In $oExcel.Application^ ERROR

>Exit code: 1 Time: 0.395

_CloseExcel()

Func _CloseExcel()

$oExcel = ObjGet("", "Excel.Application")

For $element In $oExcel.Application.Workbooks

If $element.FullName <> "" Then

;MsgBox(0,"",$element.FullName)

$element.Save

$element.Close

Else

$element.Activate

$oExcel.Application.Dialogs(5).Show

EndIf

Next

$oExcel.Application.Quit

EndFunc

Link to comment
Share on other sites

This func will do just what you need:

Func _CloseExcel()
    Local $oExcel = ObjGet("", "Excel.Application")
    If IsObj($oExcel) Then
        ConsoleWrite("EXCEL: " & ObjName($oExcel) & @lf)
        For $wbk In $oExcel.Workbooks
            ConsoleWrite("Closing workbook: " & $wbk.Name & @lf)
            $wbk.Close(True)
        Next
        $oExcel.Quit()
    EndIf
EndFunc

You don't need to check if a workbook is new (FullName property is anyway the wrong place to look - it is always set) or to call Save(), $wbk.Close(True) will save automatically or ask user for path where appropriate. But you always should check IsObj($var) before calling any methods on it.

UDFS & Apps:

Spoiler

DDEML.au3 - DDE Client + Server
Localization.au3 - localize your scripts
TLI.au3 - type information on COM objects (TLBINF emulation)
TLBAutoEnum.au3 - auto-import of COM constants (enums)
AU3Automation - export AU3 scripts via COM interfaces
TypeLibInspector - OleView was yesterday

Coder's last words before final release: WE APOLOGIZE FOR INCONVENIENCEĀ 

Link to comment
Share on other sites

This func will do just what you need:

Func _CloseExcel()
    Local $oExcel = ObjGet("", "Excel.Application")
    If IsObj($oExcel) Then
        ConsoleWrite("EXCEL: " & ObjName($oExcel) & @lf)
        For $wbk In $oExcel.Workbooks
            ConsoleWrite("Closing workbook: " & $wbk.Name & @lf)
            $wbk.Close(True)
        Next
        $oExcel.Quit()
    EndIf
EndFunc

You don't need to check if a workbook is new (FullName property is anyway the wrong place to look - it is always set) or to call Save(), $wbk.Close(True) will save automatically or ask user for path where appropriate. But you always should check IsObj($var) before calling any methods on it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...