Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Excel create object is slow

Posted on 2016-08-11
43
Medium Priority
?
173 Views
Last Modified: 2016-08-12
Hello,

How can i speed up the Set oExcel = CreateObject("Excel.Application") process from vb.net 2015 desktop app.
Cheers
0
Comment
Question by:RIAS
  • 25
  • 14
  • 4
43 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41752368
how long does it take?

one way of speeding up could be to create the instance when the application starts (maybe in a thread if you) so that it is ready to use when you need it.
0
 
LVL 20

Expert Comment

by:darbid73
ID: 41752853
There are many reasons why it's running slow. First could simply be your computer. Have you tried disabling all adding etc in excel to see if that improves it? See what Microsoft here uses https://support.microsoft.com/en-us/kb/302094. They use New.

Do you first try to getObject in case the user already has it open?


I'm not sure that you should ever introduce threading into any Microsoft Office programming.
0
 

Author Comment

by:RIAS
ID: 41752860
Thanks Experts , will post the entire code in couple of hours.
0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Comment

by:RIAS
ID: 41753452
 Public Sub ExportToExcel()
        Dim ClsFrmMain As New ClsFrmMainLoad
        Dim sVer As String = ""
        Dim sVer2 As String = ""
        Dim iHandle As IntPtr
        Dim flgRemoveitem As Boolean = True
        With ClsFrmMain
            Me.TabCntrlSearchSp.SelectedIndex.ToString()
            Dim intTabnumber As Integer
            Dim IntNewExcelObj As Integer
            Dim xlapp As Excel.Application
            Dim StrTabname As String = String.Empty 'Selected table name to be used as sheetname in excel file
            Dim FlgExportExcel As Boolean = False 'Flag to set record exported to excel 
            Dim FlgExportExcelSuccess As String = "False" 'Success for excel export
            For intTabnumber = 0 To 9
                If IsNothing(dg(intTabnumber)) = False Then
                    Dim dtSelectedRows As DataTable = .CreateDataTableFromSelectedRows(dg(intTabnumber))
                    If IsNothing(dtSelectedRows) = False Then
                        If TypeOf CType(dg(intTabnumber), DataGridView).DataSource Is DataView = False Then
                            If FlgExportExcel = False Then
                                Me.Cursor = Cursors.WaitCursor
                             [b]   xlapp = New Excel.Application '*** Create excel app only once.[/b]
                                Application.DoEvents()
                                IntNewExcelObj = 0
                            End If
                            FlgExportExcel = True
                            '*******Open file dialog for the path  *******************
                            If IntNewExcelObj = 0 Then
                                StrExcelLocation = .ReturnDevAreaPath()
                            End If
                            '*******End of Open file dialog for the path **************
                            Select Case intTabnumber
                                Case 0
                                    StrTabname = "Dy"
                                Case 1
                                    StrTabname = "Corr"
                                Case 2
                                    StrTabname = "Directory"
                                Case 3
                                    StrTabname = "Inter"
                                Case 4
                                    StrTabname = "St"
                                Case 5
                                    StrTabname = "REFERENCE"
                                Case 6
                                    StrTabname = "REQUEST"
                                Case 7
                                    StrTabname = "CAR"
                                Case 8
                                    StrTabname = "NEW_SUPPLIER_FORM"
                                Case 9
                                    StrTabname = "CLINIC"
                            End Select
                     [b]       FlgExportExcelSuccess = .ExportToExcel(IntNewExcelObj, dtSelectedRows, StrExcelLocation, StrTabname, xlapp)[/b]
                            Me.Cursor = Cursors.WaitCursor
                            IntNewExcelObj = 1
                        End If
                    End If
                End If

                If intTabnumber = 9 And FlgExportExcelSuccess = "True" Then
                    Dim result As Integer = MessageBox.Show("Do you want to open this Excel file?", "Excel file open", MessageBoxButtons.YesNo)
                    If result = DialogResult.Yes Then
                        .OpenExcel(StrExcelLocation) 'Open excel created
                        Application.DoEvents()
                        Me.Cursor = Cursors.WaitCursor
                    End If
                    If result = DialogResult.No Then
                        .FormatMessage(4, "", StrExcelLocation)
                    End If
                End If
            Next
            If FlgExportExcel = False Then
                .FormatMessage(5, "")
            ElseIf FlgExportExcelSuccess = "False" Then
                .FormatMessage(6, "")
            ElseIf FlgExportExcelSuccess = "Cancelled" Then
            End If
            Me.Cursor = Cursors.Default
            If IsNothing(xlapp) = True Then Exit Sub
            sVer = xlapp.Version
            iHandle = IntPtr.Zero
            If Val(sVer) >= 10 Then
                iHandle = New IntPtr(CType(xlapp.Parent.Hwnd, Integer))
                sVer = xlapp.Version
                iHandle = IntPtr.Zero
                .EnsureProcessKilled(iHandle, xlapp.Caption)
                System.Threading.Thread.Sleep(500)
            End If
        End With
    End Sub

Open in new window

 Function ExportToExcel(ByVal intCreateNew As Integer, ByVal dtGridData As DataTable, ByVal FilePath As String, ByVal StrSheetname As String, Optional ByVal xlApp As Excel.Application = Nothing) As String
        Dim xlWorkBook As Excel.Workbook = Nothing
        Dim xlWorkSheet As Excel.Worksheet = Nothing
        Application.DoEvents()
        Try
            FrmMain.Cursor = Cursors.WaitCursor
            xlApp.DisplayAlerts = False
            If intCreateNew = 0 Then
                xlApp.Workbooks.Add()
            End If
            If IsNothing(FilePath) = True Then
                xlWorkSheet = Nothing
                xlWorkBook = Nothing
                xlApp = Nothing
                FrmMain.Cursor = Cursors.Default
                Return "Cancelled"
                Exit Function
            End If
            xlApp.Workbooks(1).SaveAs(FilePath)
            Application.DoEvents()
            'If System.IO.File.Exists(FilePath) Then
            'Else
            '    xlApp.Workbooks(1).Save()
            '    xlWorkBook = xlApp.Workbooks
            'End If
            xlWorkBook = xlApp.Workbooks.Open(FilePath)
            Application.DoEvents()
            If intCreateNew = 0 Then
                xlWorkSheet = xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count)
            Else
                xlWorkBook.Worksheets.Add(After:=xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count))
                xlWorkSheet = xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count)
            End If
            xlWorkSheet.Name = StrSheetname
            With xlWorkSheet.PageSetup
                .PrintGridlines = True
                .CenterHeader = StrSheetname
                .Zoom = False
            End With
            Dim dtRowCount As Integer = dtGridData.Rows.Count
            Dim dtColCount As Integer = dtGridData.Columns.Count
            Dim objXlColHeaderData(1, dtGridData.Columns.Count) As Object
            Application.DoEvents()
            For i As Integer = 0 To dtColCount - 1
                objXlColHeaderData(0, i) = dtGridData.Columns(i).ColumnName
            Next
            Dim objXlData(dtRowCount, dtColCount) As Object
            For iRow As Integer = 0 To dtRowCount - 1
                Application.DoEvents()
                For iCol As Integer = 0 To dtColCount - 1
                    Application.DoEvents()
                    If Not IsDBNull(dtGridData.Rows(iRow).Item(iCol)) Then
                        objXlData(iRow, iCol) = dtGridData.Rows(iRow).Item(iCol)
                    Else
                        objXlData(iRow, iCol) = ""
                    End If
                Next
            Next
            Dim xlRange As Excel.Range = xlWorkSheet.Range("A1")
            xlRange = xlRange.Resize(dtRowCount + 1, dtColCount)
            xlRange.Value = objXlColHeaderData
            xlWorkSheet.Range(xlWorkSheet.Cells(1, 1), xlWorkSheet.Cells(1, dtColCount)).Font.Bold = True
            xlRange = xlWorkSheet.Range("A2")
            xlRange = xlRange.Resize(dtRowCount, dtColCount)
            xlRange.Value = objXlData
            With xlWorkSheet
                .Range(.Cells(1, 1), .Cells(1, 1)).Select()
            End With
            With xlWorkSheet.Application.ActiveWindow
                .SplitColumn = 0
                .SplitRow = 1
            End With
            xlWorkSheet.Cells.EntireColumn.AutoFit()
            xlWorkSheet.Application.ActiveWindow.FreezePanes = True
            Application.DoEvents()
            xlWorkBook.Save()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "ErrorIn ExportToExcel", MessageBoxButtons.OK, MessageBoxIcon.Error)
            xlWorkSheet = Nothing
            xlWorkBook = Nothing
            xlApp = Nothing
            FrmMain.Cursor = Cursors.Default
        Finally
            FrmMain.Cursor = Cursors.Default
        End Try
        Return "True"
    End Function

Open in new window

0
 

Author Comment

by:RIAS
ID: 41753456
Is it possible to give an example of


Do you first try to getObject in case the user already has it open?

Thanks
0
 
LVL 20

Assisted Solution

by:darbid73
darbid73 earned 1000 total points
ID: 41753463
No problem.

See MSDN. It actually uses as an example Excel.

' Test to see if a copy of Excel is already running. 
Private Sub testExcelRunning()
    On Error Resume Next 
    ' GetObject called without the first argument returns a 
    ' reference to an instance of the application. If the 
    ' application is not already running, an error occurs. 
    Dim excelObj As Object = GetObject(, "Excel.Application")
    If Err.Number = 0 Then
        MsgBox("Excel is running")
    Else
        MsgBox("Excel is not running")
    End If
    Err.Clear()
    excelObj = Nothing 
End Sub

Open in new window

Code from Microsoft in case the link is dead.

I always use code like this first for Office as it can be that the user already has an instance open.  Especially when it comes to Outlook which is usually always on.


Here is an alternative. Which is similar.
0
 

Author Comment

by:RIAS
ID: 41753479
darbid73,

Any suggestion on threading to create object on the app load.
And then I can use getobject
0
 
LVL 20

Expert Comment

by:darbid73
ID: 41753538
I am not an expert on threading and office.  It is my opinion that you simply should not mix threading and the office object model.  You can use a thread to for example go and perform a HTTP request or query a SQL database but you need to come back to the UI thread when you use the Office Object model.

If you do a Google Search on this topic you will find a massive amount of information and opinions on it.  So I am neither alone with my opinion nor right as I am sure people will give example where you can use threads.

Maybe Eric could elaborate on how he thought you might do it.
0
 

Author Comment

by:RIAS
ID: 41753540
Cheers darbid73!

Hello Éric Moreau,

Any suggestions on threading!
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753671
before going to the threading option:
-how long does it take? (I already asked this)
-How long does it take to just open Excel standalone?
0
 

Author Comment

by:RIAS
ID: 41753673
It takes around 4-5 minutes
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753675
4 to 5 minutes to execute "Set oExcel = CreateObject("Excel.Application")" ?
0
 

Author Comment

by:RIAS
ID: 41753678
Yes
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753687
just that line, not the whole process takes 4-5 minutes?

how long does it take to start Excel standalone?

I have never seen it taking so long. Have you checked your computer for viruses, malware, ... ?
0
 

Author Comment

by:RIAS
ID: 41753689
Hi,
my application is running on Citrix and just to open ,i.e New excel it takes 4-5 minutes.
Yes,It is free of virus ,malware etc
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753702
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 

Author Comment

by:RIAS
ID: 41753704
4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
 

Author Comment

by:RIAS
ID: 41753707
and then the rest of the code gets executed.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753716
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 

Author Comment

by:RIAS
ID: 41753719
Eric,
Excel from office opens very opens quickly.
0
 

Author Comment

by:RIAS
ID: 41753721
but from app it takes 4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753727
it is surely related to Citrix.

what if you run this application from your computer (instead of from a Citrix session)?

are you using Early binding or late binding (https://support.microsoft.com/en-us/kb/245115)? how is your oExcel declared?
0
 

Author Comment

by:RIAS
ID: 41753730
Its the same.
      xlapp = New Excel.Application '*** Create excel app only once.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753743
again, what if you run this application from your computer (instead of from a Citrix session)?
0
 

Author Comment

by:RIAS
ID: 41753744
Its the same if I run the app from my PC rather than Citrix
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753760
I have never seen creating an instance of Excel taking 4-5 minutes.

To debug the issue, I would create a brand new dummy application containing only a form. On that form I would add a button that would only do a "dim x as new Excel.Application" (you will need a reference to Excel). I would test this on my computer and then on Citrix. Can you do that?
0
 

Author Comment

by:RIAS
ID: 41753764
Yes
0
 

Author Comment

by:RIAS
ID: 41753776
Eric,

little faster than the earlier one.But still slow
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753781
on your own PC without having Citrix around? This is just not making any sense! Do you have another computer on which you can test? Can you turn off your antivirus for a minute (you might disconnect your computer from the network for that period)?
0
 

Author Comment

by:RIAS
ID: 41753789
Eric, its much faster
0
 
LVL 20

Expert Comment

by:darbid73
ID: 41753792
Are sure that when you start excel manually with a mouse click that excel starts at a normal speed?
0
 

Author Comment

by:RIAS
ID: 41753795
Yes ,it does start at normal speed
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753803
>>Eric, its much faster

what have you done to be much faster? the other computer? the disabling of the antivirus? disconnection of antivirus?

You need to give us as much information as you can because we just cannot guess what is happening on your side!
0
 

Author Comment

by:RIAS
ID: 41753807
Its basically not on citrix and have disabled antivirus.
0
 

Author Comment

by:RIAS
ID: 41753809
Eric,
Should I try threading ?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753822
threading will never make a process faster. it will just help if you can span 2 or more processes at the same time

so if you found that the antivirus is your issue, dig into that direction. Which one is it? any updates available for it? Anything on their support site? ...
0
 

Author Comment

by:RIAS
ID: 41753825
Its Mcafee
0
 

Author Comment

by:RIAS
ID: 41753827
Will try threading.
Any suggestion on how to go for asynchronous threading just to create excel
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41753829
>>Will try threading.

it won't solve your issue.
0
 

Author Comment

by:RIAS
ID: 41753832
Cannot disable mcafee on citrix.
0
 

Author Comment

by:RIAS
ID: 41753833
need to have a workaround
0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 1000 total points
ID: 41753857
Your best bet is to contact McAfee. They are surely aware of something that can fix your issue.

As I already said, threading is not your solution. It will just take 4-5 minutes to the thread to complete but you won't have access to your Excel object faster. So it is totally useless to go that way.

A real workaround would be to use a library to replace Excel like http://www.aspose.com/products/cells/net
0
 

Author Closing Comment

by:RIAS
ID: 41753859
Cheers! Cant thank you enough for being so patient and guiding in the right direction
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Integration Management Part 2
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

824 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question