Monday, April 11, 2011

Function to verify whether any excel instance is open or not. If opened terminate the same.

Function IsAnyExcelInstancesOpen 'As Boolean

    IsAnyExcelInstancesOpen = True

    Dim objWMIService, objProcess, ProcessCollection
    Dim strComputer, strMessage
    Dim bolTerminate
    Dim InputUserSelection
    ' Make it true if you want to terminate process without any user;s permission.
    bolTerminate = False
   
    strComputer = "."
   
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
   
    Set ProcessCollection = objWMIService.ExecQuery("Select * from Win32_Process")
   
    For Each objProcess in ProcessCollection
    If StrComp(objProcess.Name, "Excel.exe", 1) = 0 Then
        ' If true it will terminate process without any message or intimation
        If boolTerminate Then
            objProcess.Terminate()
        ' It will ask user(Permission) input "Yes" to terminate excel instance opened.     
        Else
           
            strMessage = "An Instance of Excel is running on the Machine. The Framework needs all the Excel instances to be closed for running the Tests." & vbCr & vbCr &_
                "Do you want the Framework to CLOSE all the instances of the Excel?" & vbCr & vbCr &_
                " - Yes:" & vbCr & "Click on Yes to close all the instances of Excel and proceed with the Test Execution." & vbCr & vbCr &_
                " - No :" & vbCr & "Click on No to Stop the test execution and close the Excel files manualy." & vbCr & "--" & vbCr &_
                "Note: All unsaved data in the open excel files will be lost on clicking Yes."
               
            oUserSelection = MsgBox(strMessage, vbYesNo + vbExclamation , "Excel Instances Open")
               
            If oUserSelection = vbYes Then
               
                boolTerminate = True
                objProcess.Terminate()
               
            Else
           
                Exit Function
               
            End If
           
        End If
       
    End If
   
    Next

    IsAnyExcelInstancesOpen = False
   
End Function

No comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | JCpenney Printable Coupons