HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Optimizing this Excel automation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisoptimizingexcelautomation

Problem

The createReport method takes around 30 seconds to execute and I was wondering how I could optimize it. I'm using the Interop.Excel class and the workbook I'm importing to is very formula intensive.

`Dim UserDate As New Data_Entry_Form.UserDate
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xlSourceRange, xlDestRange As Excel.Range
Dim path As String = Application.StartupPath
Dim dt As New DataTable
Public Sub New()

End Sub
Sub createReport(dt As DataTable) ' this procedure determines the flow of the excel manipulation'
openfile("2012 Master.xlsx")
debugging(False)
putfilesIntoYTD(dt)
save("test.xlsx")
closexl()
cleanup()
MsgBox("fin")
End Sub
Sub closexl()
xlWorkBook.Close()
xlApp.Quit()
End Sub
Sub cleanup() ' Releases all of the com objects to object not have excel running as a process after this method finishes'
GC.Collect()
GC.WaitForPendingFinalizers()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSourceRange)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End Sub
Sub debugging(mode As Boolean) 'Determines if we want to display anything during the dubugging process'
If mode = True Then
xlApp.DisplayAlerts = True
xlApp.Visible = True
Else
xlApp.DisplayAlerts = False
xlApp.Visible = False

End If
End Sub
Sub putfilesIntoYTD(dt As DataTable)
'dt = CType(dbTools.getYTD(startDate, endDate), DataTable)'
Dim fileNum() As String = convertColumntoArray(dt, 0)
Dim dateRecorded() As String = convertColumntoArray(dt, 1)
Dim closerAndTypeCode() As String = convertColumntoArray(dt, 2)
xlSourceRange = xlWorkSheet.Range("N2:N" & fileNum.Length)
xlSourceRange.Value = fileNum
xlSourceRange = xlWorkSheet.R

Solution

There is definetely a way to improve that even though the excel sheet has a lot of formulas.
In VBA there is an:

Application.Calculation = xlManualCalculation


That can be used to help dramatically improve the time it takes, when the problem is many formulas in a sheet. And then in the end you should turn it back to automatic.

As you are using VB with a connection to the Excel Workbook through a COM, the way to do it is very similar. It is:

ExcelApp.Calculation = XlCalculation.xlCalculationManual


Where ExcelApp is the excel application object.

Code Snippets

Application.Calculation = xlManualCalculation
ExcelApp.Calculation = XlCalculation.xlCalculationManual

Context

StackExchange Code Review Q#15966, answer score: 2

Revisions (0)

No revisions yet.