Results 1 to 18 of 18

Thread: Excel Automation Issue

  1. #1

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Thumbs up Excel Automation Issue

    Hi all,
    I am trying to automate excel. And creating excel object as
    Code:
    oExcel = CreateObject("Excel.Application")
    And trying to close/kill(Kill ) the Excel in Process window using

    Code:
     For Each P as Process In Process.GetProcessByName("Excel") 
        if p.MainWindowHandle.ToInt32 == oExcel )
         p.kill
       end if
     Next
    But the P.MainWindowHandle.ToInt32 is always 0

    I have tried this one , Which works for simple methods and not for complex methods
    Please mark you thread resolved using the Thread Tools as shown

  2. #2
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Excel Automation Issue

    CreateObject does NOT return a window handle!
    It returns a reference to your object.

    Use FindWindow API:

    vb.net Code:
    1. <DllImport("user32.dll")> Public Shared Function _
    2.          FindWindow(ByVal strClassName As String, ByVal strWindowName _
    3.              As String) As IntPtr
    4.     End Function

    And closing Excel like that is awfully wrong and may lead to memory leaks (do remember that it's built on COM technology).

    To close your excel instance you should use:

    oExcel.Quit method (option strict must be off to allow late binding).

    If you want excel interoperability download Microsoft.Office.Interop assemblies pack to do it properly.

    For Office 2003:
    http://www.microsoft.com/downloads/d...displaylang=en

    For Office 2007:
    http://www.microsoft.com/downloads/d...displaylang=en

  3. #3

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    Thanks for the post cicatrix. If I use the Findwindow method I have to give the window name. It there are more request from server then all the Window name will be same ?
    Please mark you thread resolved using the Thread Tools as shown

  4. #4
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Excel Automation Issue

    Quote Originally Posted by danasegarane View Post
    Thanks for the post cicatrix. If I use the Findwindow method I have to give the window name. It there are more request from server then all the Window name will be same ?
    On the second thought you wouldn't probably know the exact window title. Only that it starts with 'Microsoft Excel'

    Here's the article that covers the windows enumeration:
    http://support.microsoft.com/kb/183009

    But I still advise you not to kill Excel like that.
    Use its native Quit method.

    And one more important thing:
    If you create an Excel instance with CreateObject it won't have a window at all unless you do:
    oExcel.Visible = True

  5. #5
    Hyperactive Member koolprasad2003's Avatar
    Join Date
    May 2007
    Location
    India
    Posts
    443

    Arrow Re: Excel Automation Issue

    why don't you use following code

    Code:
            Dim oXL As Excel.Application
            Dim oWB As Excel.Workbook
            Dim oSheet As Excel.Worksheet
    it is easy to close and kill EXCEL object

    Code:
            oSheet = Nothing
            oWB.Close()
            oWB = Nothing
            oXL.Quit()
            oXL = Nothing
    System.GC.Collect()
    System.GC.WaitForPendingFinalizers()
    MCP, MCTS, Microsoft MVP [Asp.Net/IIS]

    For more .NET development tips visit .NET Tips

    If the post is useful then please Rate it

  6. #6

  7. #7
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel Automation Issue

    And trying to close/kill(Kill ) the Excel in Process window using
    I would suggest you not to use this method but close it the proper way.

    Here is an example.

    Code:
    Imports Excel = Microsoft.Office.Interop.Excel
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
    
            xlApp = New Excel.ApplicationClass
            
            '~~> Opening existing  workbook
            xlWorkBook = xlApp.Workbooks.Open("c:\MyFile.xlsx")
            '~~> Working with the first Sheet
            xlWorkSheet = xlWorkBook.Worksheets("sheet1")
            
            '~~> Writing to a cell A1
            xlWorkSheet.Cells(1, 1) = "danasegarane"
            
            '~~> Closing the workbook
            '~~> Need to include one more line if you want to save it via code
            xlWorkBook.Close()
            xlApp.Quit()
            
            '~~> Clean Up
            releaseObject (xlApp)
            releaseObject (xlWorkBook)
            releaseObject (xlWorkSheet)
    
        End Sub
    
        Private Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject (obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
    
    End Class
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  8. #8
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Excel Automation Issue

    One addition:
    vb Code:
    1. xlWorkBook.Close(SaveChanges:=False)
    Or else there will be a prompt for saving changes.

  9. #9

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    Quote Originally Posted by koolsid View Post
    I would suggest you not to use this method but close it the proper way.

    Here is an example.

    Code:
    Imports Excel = Microsoft.Office.Interop.Excel
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
    
            xlApp = New Excel.ApplicationClass
            
            '~~> Opening existing  workbook
            xlWorkBook = xlApp.Workbooks.Open("c:\MyFile.xlsx")
            '~~> Working with the first Sheet
            xlWorkSheet = xlWorkBook.Worksheets("sheet1")
            
            '~~> Writing to a cell A1
            xlWorkSheet.Cells(1, 1) = "danasegarane"
            
            '~~> Closing the workbook
            '~~> Need to include one more line if you want to save it via code
            xlWorkBook.Close()
            xlApp.Quit()
            
            '~~> Clean Up
            releaseObject (xlApp)
            releaseObject (xlWorkBook)
            releaseObject (xlWorkSheet)
    
        End Sub
    
        Private Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject (obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
    
    End Class
    I tried this before. And the thing is that I have 30 sheets in a WorkBook and trying to copy to another workbook cause the excel not closing from task list. Let me try once again
    Please mark you thread resolved using the Thread Tools as shown

  10. #10
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Excel Automation Issue

    Do you invoke Quit method?

    And you should either save your changes using Save method
    And use Workbook.Close method with parameters SaveChanges

  11. #11
    Hyperactive Member koolprasad2003's Avatar
    Join Date
    May 2007
    Location
    India
    Posts
    443

    Arrow Re: Excel Automation Issue

    Quote Originally Posted by koolsid View Post
    I would suggest you not to use this method but close it the proper way.[/CODE]
    exactly koolsid, by KILL method other excel object could get killed.....

    so better to get reference of
    Code:
    Microsoft.Excel.Introp
    library
    and use the Application and Worksheet object. it has the saparate methods for Closing the EXCEL object
    MCP, MCTS, Microsoft MVP [Asp.Net/IIS]

    For more .NET development tips visit .NET Tips

    If the post is useful then please Rate it

  12. #12

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    Quote Originally Posted by cicatrix View Post
    Do you invoke Quit method?

    And you should either save your changes using Save method
    And use Workbook.Close method with parameters SaveChanges

    Yes I called that method ..

    From MSDN :

    When you automate a Microsoft Office application from Microsoft Visual Basic .NET or Microsoft Visual C# .NET, the Office application does not quit when you call the Quit method.
    Please mark you thread resolved using the Thread Tools as shown

  13. #13

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    I was testing with this one.

    vb Code:
    1. Private oexcel As Excel.Application
    2.     Dim oSourceWorkBooks_1 As Excel.Workbooks
    3.     Dim oSourceWorkBook1 As Excel.Workbook
    4.  
    5.     Dim oDestinationWorkBooks_1 As Excel.Workbooks
    6.     Dim oDestinationWorkBook_1 As Excel.Workbook
    7.     Dim oSourceWorkSheets_1 As Excel.Sheets
    8.  
    9.     Dim oDataBaseSheet As Excel.Worksheet
    10.     Dim oTemplateSheet As Excel.Worksheet
    11.     Dim oDestinationWorkSheets_1 As Excel.Sheets
    12.     Dim oDestinationWorkSheet_1 As Excel.Worksheet
    13.  
    14.  
    15.     Sub New(ByVal file As String)
    16.         Dim filename As String = Path.Combine(Path.GetTempPath, Path.GetTempFileName)
    17.         Dim _filename As String = ""
    18.         Dim b As Excel.Workbook
    19.  
    20.         oexcel = CreateObject("Excel.Application")
    21.  
    22.         oexcel.Visible = True
    23.         oexcel.DisplayAlerts = False
    24.         oDestinationWorkBooks_1 = oexcel.Workbooks
    25.         oDestinationWorkBook_1 = oDestinationWorkBooks_1.Add
    26.         oSourceWorkBooks_1 = oexcel.Workbooks
    27.  
    28.         oSourceWorkBook1 = oSourceWorkBooks_1.Open(file)
    29.  
    30.         oSourceWorkSheets_1 = oSourceWorkBook1.Sheets
    31.         oTemplateSheet = oSourceWorkSheets_1("Template")
    32.         oDataBaseSheet = oSourceWorkSheets_1("Database")
    33.  
    34.         oDestinationWorkSheets_1 = oDestinationWorkBook_1.Sheets
    35.         oDestinationWorkSheet_1 = oDestinationWorkSheets_1("Sheet1")
    36.  
    37.       'Copy sheets from Book1 to 2
    38.        [B][U] For index As Integer = 1 To 10
    39.  
    40.             oTemplateSheet.Copy(oDestinationWorkSheet_1)
    41.         Next[/U][/B]
    42.  
    43.         'End With
    44.         'oSourceWorkBook1 = oSourceWorkBooks1.Open(file)
    45.         marshal(oTemplateSheet)
    46.         marshal(oDataBaseSheet)
    47.         marshal(oSourceWorkSheets_1)
    48.         oSourceWorkSheets_1 = Nothing
    49.         oDataBaseSheet = Nothing
    50.         oTemplateSheet = Nothing
    51.  
    52.         oSourceWorkBook1.Close()
    53.         marshal(oSourceWorkBooks_1)
    54.         marshal(oSourceWorkBook1)
    55.         oDestinationWorkBooks_1.Close()
    56.         marshal(oDestinationWorkBooks_1)
    57.         marshal(oDestinationWorkBook_1)
    58.         oexcel.Quit()
    59.         marshal(oexcel)
    60.         System.IO.File.Delete(filename)
    61.         System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oexcel)
    62.  
    63.  
    64.  Private Sub marshal(ByVal o As Object)
    65.         If Not o Is Nothing Then
    66.             System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
    67.             o = Nothing
    68.         End If
    69.     End Sub



    It was releasing correctly upto the marked . While I try to copy sheets from WorkBook1 to WorkBook2 it was not releasing after adding that copy method
    Last edited by danasegarane; Feb 1st, 2010 at 10:45 AM.
    Please mark you thread resolved using the Thread Tools as shown

  14. #14
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel Automation Issue

    I tried this before. And the thing is that I have 30 sheets in a WorkBook and trying to copy to another workbook cause the excel not closing from task list. Let me try once again
    Did you try it? I tried copying sheets using my code (with slight amendments of course) and it works just fine....
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  15. #15

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    I have replied in post no # 13
    Please mark you thread resolved using the Thread Tools as shown

  16. #16
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Excel Automation Issue

    The basics of excel or office automation is to create object variables for each level down the object model. Then destroy each in reverse order. So parent to child creation. Then child to parent destruction.

    Dont Implicitly create instances as those will retain an open reference to the object and prevent the object variable from being destroyed.

    Dont create an object variable reference more then one level down. This is an example of two levels down and "could" be an issue.

    xlWorkBook = xlApp.Workbooks.Open("c:\MyFile.xlsx")

    Better as ...

    xlWorkBooks = xlApp.WorkBooks
    xlWorkBook = xlWorkBooks.Open("C:\MyBook.xlsx")

    When properly created, destruction will be complete with no leftover open references. You should never really need to use .ReleaseComObject or .FinalReleaseComObject
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  17. #17
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Excel Automation Issue

    Oh yea and if you need to install the Office Interop (PIA's) please see the link in my Office Dev FAQ.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  18. #18

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: Excel Automation Issue

    I am attaching one sample program here.

    The excel object removed from TaskManager without this lines

    Code:
    #
    For index As Integer = 1 To 10
                oTemplateSheet.Copy(oDestinationWorkSheet_1)
    
           Next
    With addition of these lines the excel is not release from TaskManager
    Attached Files Attached Files
    Please mark you thread resolved using the Thread Tools as shown

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width