Overlapping of images while pasting from one to another excel using VB - vb.net

I am trying to paste few images from one excel to another, but facing an issue in it. the images are overlapping on each other., and even the size is very small.Below is the code of what i have tried.
If Source = ESNAME Then
Dim shp As Microsoft.Office.Interop.Excel.Shape
Dim lCol As Integer = 0
Dim I As Integer = 1
'~~> Loop through all shapes and find the last col of the shape
For Each shp In WS.Shapes
If shp.BottomRightCell.Column > lCol Then _
lCol = shp.BottomRightCell.Column
With WS
'~~> Find actual last Row
Dim LastRow As Integer = I
Dim LastColumn As Integer = I
Dim str As String = "B" & I & "#"
'~~> Check if we have the correct last columnm
If LastColumn < lCol Then LastColumn = lCol
.Range(str.Replace("#", ":") & Split(.Cells(, LastColumn).Address, "$")(1) & LastRow).Copy()
Dim sheet As Microsoft.Office.Interop.Excel.Worksheet
sheet = Nothing
sheet = DW.Worksheets(1)
sheet.Paste()
End With
I = I + 1
Next
End If
Thanks in advance.

Let's say your Workbook1 looks like this
Try this code (TRIED AND TESTED in VS 2010 + OFFICE 2010)
Code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'~~> Define your Excel Objects
Dim xlApp As New Excel.Application
Dim xlWorkBook1 As Excel.Workbook = Nothing
Dim xlWorkBook2 As Excel.Workbook = Nothing
Dim xlWorkSheet1 As Excel.Worksheet = Nothing
Dim xlWorkSheet2 As Excel.Worksheet = Nothing
'~~> Display Excel
xlApp.Visible = True
'~~> Open relevant excel files and set your objects
xlWorkBook1 = xlApp.Workbooks.Open("C:\book1.xlsx")
xlWorkSheet1 = xlWorkBook1.Sheets("Sheet1")
xlWorkBook2 = xlApp.Workbooks.Open("C:\book2.xlsx")
xlWorkSheet2 = xlWorkBook2.Sheets("Sheet2")
Dim xlShp As Excel.Shape = Nothing
Dim xlShape As Excel.Shape = Nothing
For Each xlShp In xlWorkSheet1.Shapes
xlShp.Copy()
xlWorkSheet2.Paste(Destination:=xlWorkSheet2.Range("A1"))
Next
Dim col1 As New Point(10, 10)
Dim col2 As New Point(col1.X * 2 + xlWorkSheet2.Shapes(0).Width, 10)
Dim stdHeight As Integer = CType(xlWorkSheet2.Shapes(0), Excel.Shape).Height + 5
For i As Integer = 0 To xlWorkSheet2.Shapes.Count - 1 Step 2
xlShape = xlWorkSheet2.Shapes(i)
xlShape.Left = col1.X
xlShape.Top = col1.Y + i * stdHeight
xlShape = xlWorkSheet2.Shapes(i + 1)
xlShape.Left = col2.X
xlShape.Top = col2.Y + i * stdHeight
Next
'~~> Save the file
xlWorkBook2.Save()
'~~> Close the File
xlWorkBook1.Close (False)
xlWorkBook2.Close (False)
'~~> Quit the Excel Application
xlApp.Quit()
'~~> Clean Up
releaseObject (xlShp)
releaseObject (xlShape)
releaseObject (xlWorkSheet1)
releaseObject (xlWorkSheet2)
releaseObject (xlWorkBook1)
releaseObject (xlWorkBook2)
releaseObject (xlApp)
End Sub
'~~> Release the objects
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
Workbook 2 Output

Related

Finding Last Blank Cell Of The Excel (In Column Range H8:H38), and Updating Blank Cell In Desired Range - VB.NET

Sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
'Set which worksheet tobe modified
oSheet = oBook.Worksheets(1)
'This will find the lastRow in the sheet
'Dim lastRow As Integer = 7
Dim ETLastRow As Integer = oSheet.usedrange.rows.count
'This is next emptyRow in the sheet
Dim ETemptyRow As Integer = ETLastRow + 1
'edit last empty row val on column 8
Dim columnToMod As Integer = 8
oSheet.Cells(ETemptyRow, columnToMod).value = passedData
ETLastRow = oSheet.usedrange.rows.count
ETemptyRow = ETLastRow + 1
'This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
TextBox12.AppendText("Sucess!!!" + vbCrLf + vbCrLf)
End Sub
Giving wrong last row, if in excel doc already have a table with formula in it.
Output Preview:
Targeting In Cell Range (H8:H38)
[1]: https://i.stack.imgur.com/D4RT5.png
But Output In Cell Range (H40:H)
[2]: https://i.stack.imgur.com/0wufs.png
Hehehe, i found the solutions,
Thanks to #StoriKnow & his answer there:
Here is my latest sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As New Object
Dim oBook As New Object
Dim oSheet As New Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
oSheet = oBook.Worksheets(1)
Try
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 8 'column H has a value of 8
rowCount = oSheet.Cells(oSheet.Rows.Count, sourceCol).End(Excel.XlDirection.xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 8 To rowCount
currentRowValue = oSheet.Cells(currentRow, sourceCol).Value
If (currentRowValue Is Nothing) Or (currentRowValue = "") Then
'oSheet.Cells(currentRow, sourceCol).Select
Dim preview As String = currentRow
TextBox12.AppendText(preview + " ")
oSheet.Cells(currentRow, sourceCol).Select
oSheet.Cells(currentRow, sourceCol).value = passedData
Exit Try
End If
Next
Finally
''' DO NOTHING
End Try
''This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
end Sub
Output that achived:

Export queries from Access-Form to Excel with Loop in VBA

I want to Export large data stock from Access to Excel. I'm doing that with a form.
My code with "DoCmd.TransferSpreadsheet acExport..." works normally, but the program breaks off because of the large data stock.
Perhaps with queries I can solve this Problem, or what do you think?
I am thankful for each tip! =)
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'=======================
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'''PPT
Sub pptExoprort()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim slideNum As Integer
Dim chartName As String
Dim tableName As String
Dim PPTCount As Integer
Dim PPSlideCount As Long
Dim oPPTShape As PowerPoint.Shape
Dim ShpNm As String
Dim ShtNm As String
Dim NewSlide As String
Dim myChart As PowerPoint.Chart
Dim wb As Workbook
Dim rngOp As Range
Dim ro As Range
Dim p As Integer
Dim v, v1, v2, v3, Vtot, VcaGr
Dim ws As Worksheet
Dim ch
Dim w As Worksheet
Dim x, pArr
Dim rN As String
Dim rt As String
Dim ax
Dim yTbN As String
'Call InitializeGlobal
''start year offset
prodSel = shtSet.Range("rSelProd")
x = shtSet.Range("rngMap").Value
pArr = fretPrVal(x, prodSel)
TY = 11 'number of years in chart
ThisWorkbook.Activate
Set w = ActiveSheet
Set PPApp = GetObject("", "Powerpoint.Application") '******************
PPTCount = PPApp.Presentations.Count
If PPTCount = 0 Then
MsgBox ("Please open a PPT to export the Charts!")
Exit Sub
End If
Set PPPres = PPApp.ActivePresentation '******************
For j = 0 To UBound(pArr)
If j = 0 Then
rN = "janport"
slideNum = 3
yTbN = "runport"
Else
rN = "janprod" & j
slideNum = 3 + j
yTbN = "runprod" & j
End If
chartName = "chtSalesPort"
Set PPSlide = PPPres.Slides(slideNum) '**************
PPApp.ActiveWindow.View.GotoSlide PPSlide.SlideIndex
Set myChart = PPSlide.Shapes(chartName).Chart '******************
myChart.ChartData.Activate '********************
Set wb = myChart.ChartData.Workbook '***********
Set ws = wb.Worksheets(1) '**************
Set rngOp = w.Range(rN).Offset(0, 1).Resize(12, 6)
Set ro = rngOp
' v1 = ro.Offset(1, 22).Resize(Lc, 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$B$" & Ty + 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$" & Chr(Lc + 1 + 64) & "$" & Ty + 1)
ws.Range("B2:g13").ClearContents '***********
rngOp.Copy '**********
ws.Range("B2:g13").PasteSpecial xlPasteValues '******************
End Sub
Sub Picture62_Click()
Dim charNamel As String
Dim leftm As Integer
Dim toptm As Integer
charNamel = "Chart 1"
leftm = 35
toptm = 180
Call chartposition(leftm, toptm, charNamel)
End Sub
Sub chartposition(leftm, toptm, charNamel)
ActiveSheet.ChartObjects(charNamel).Activate
'First we declare the variables we will be using
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht As Excel.ChartObject
Dim activslidenumber As Integer
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
' If newPowerPoint.Presentations.Count = 0 Then
' newPowerPoint.Presentations.Add
' End If
'Show the PowerPoint
newPowerPoint.Visible = True
On Error GoTo endd:
activslidenumber = Str(GetActiveSlide(newPowerPoint.ActiveWindow).SlideIndex)
Set activeSlide = newPowerPoint.ActivePresentation.Slides(activslidenumber)
ActiveChart.ChartArea.Copy
On Error GoTo endddd:
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteDefault).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteOLEObject, DisplayAsIcon:=msoFalse).Select
endddd:
newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = leftm
newPowerPoint.ActiveWindow.Selection.ShapeRange.Top = toptm
GoTo enddddd:
endd:
MsgBox ("Please keep your PPT file opened")
enddddd:
End Sub

Visual Studio 2015 - Manipulating Excel?

I have 750 Excel files that I want to
clean by deleting columns of data that have a heading with an asterisk,
then take some of that data and put it in a new workbook worksheet, and other data into the same workbook worksheet, and some other data into a second new workbook.
I created a WPF project in Visual Studio 2015 with a little dialog box with 2 radio buttons for
clean data,
produce new files.
This is my VB code:
Class MainWindow
Dim wb As Microsoft.Office.Interop.Excel._Workbook
Dim ws As Microsoft.Office.Interop.Excel._Worksheet
Dim iCol As Integer
Dim strName As String
Dim iIndex As Integer
Dim strPath As String
Dim strFile As String
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
If cleanRadioButton.IsChecked = True Then
strPath = "c:\test\old\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
wb = wb.Open(Filename:=strPath & strFile)
'Loop through the sheets.
For iIndex = 1 To Application.Worksheets.Count
ws = Application.Worksheets(iIndex)
'Loop through the columns.
For iCol = 1 To ws.UsedRange.Columns.Count
'Check row 1 of this column for the char of *
If InStr(ws.Cells(10, iCol).Value, "*") > 0 Then
'We have found a column with the char of *
ws.Columns(iCol).EntireColumn.Delete
ws.Columns(iCol + 1).EntireColumn.Delete
ws.Columns(iCol + 2).EntireColumn.Delete
End If
Next iCol
Next iIndex
wb.SaveAs(Filename:="C:\test\new\" & wb.Name, FileFormat:=xlOpenXMLWorkbook)
wb.Close(SaveChanges:=False)
strFile = Dir()
Loop
MessageBox.Show("The csv files have now been cleaned. Congrats.")
Else inputRadioButton.IsChecked = True
MessageBox.Show("The data has now been split into Trajectory and ForcePlate input files. High 5.")
End If
End Sub
End Class
I get 3 errors but can't work out how to solve them.
a) Worksheets is not a member of Application [line 19]
b) Worksheets is not a member of Application [line 20]
c) 'xlOpenXMLWorkbook' is not declared. It may be inaccessible due to its protection level.
For a) and b), the pattern is :
Application.Workbooks.Worksheets
For c), easiest way out :
Go into VBE from Excel (Alt + F11)
Press F2 to display the Object Browser
Look for xlOpenXMLWorkbook
Result : Const xlOpenXMLWorkbook = 51 (&H33)
So, just replace it by the value 51!
Here is your amended code :
Class MainWindow
Dim wb As Microsoft.Office.Interop.Excel._Workbook
Dim ws As Microsoft.Office.Interop.Excel._Worksheet
Dim iCol As Integer
Dim strName As String
Dim iIndex As Integer
Dim wbIndex As Integer
Dim strPath As String
Dim strFile As String
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
If cleanRadioButton.IsChecked = True Then
strPath = "c:\test\old\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
wb = wb.Open(Filename:=strPath & strFile)
'Loop through the sheets.
For wbIndex = 1 To Application.Workbooks.Count
For iIndex = 1 To Application.Workbooks(wbIndex).Worksheets.Count
Ws = Application.Workbooks(wbIndex).Worksheets(iIndex)
'Loop through the columns.
For iCol = 1 To Ws.UsedRange.Columns.Count
'Check row 1 of this column for the char of *
If InStr(Ws.Cells(10, iCol).Value, "*") > 0 Then
'We have found a column with the char of *
Ws.Columns(iCol).EntireColumn.Delete
Ws.Columns(iCol + 1).EntireColumn.Delete
Ws.Columns(iCol + 2).EntireColumn.Delete
End If
Next iCol
Next iIndex
Next wbIndex
'Const xlOpenXMLWorkbook = 51 (&H33)
wb.SaveAs(Filename:="C:\test\new\" & wb.Name, FileFormat:=51)
wb.Close(SaveChanges:=False)
strFile = Dir()
Loop
MessageBox.Show ("The csv files have now been cleaned. Congrats.")
Else: inputRadioButton.IsChecked = True
MessageBox.Show ("The data has now been split into Trajectory and ForcePlate input files. High 5.")
End If
End Sub
End Class
To reference a worksheet yau can use either ws = wb.Worksheets(1) or ws = wb.Worksheets("Sheet1") or ws = excelApp.ActiveWorkbook.Worksheets(1) and to use xlOpenXMLWorkbook use the name of the corresponding Enum XlFileFormatas well: XlFileFormat.xlOpenXMLWorkbook.
This simplified example opens the workbook Test.xlsx, writes text in cell A1 and saves it to new folder.
Imports System.IO
Imports Microsoft.Office.Interop.Excel
Public Class MainWindow
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim excelApp As Application
Dim wb As _Workbook
Dim ws As _Worksheet
Dim rng As Range
Dim strPathOld = "c:\temp\old"
Dim strPathNew = "c:\temp\new"
' get excel application reference
excelApp = New Application
excelApp.Visible = True
excelApp.ScreenUpdating = True
' open the workbook
wb = excelApp.Workbooks.Open(Path.Combine(strPathOld, "Test.xlsx"))
' set reference to the sheet with index 1
ws = wb.Worksheets(1)
' or use sheet name
' ws = wb.Worksheets("Sheet1")
' or use ActiveWorkbook if it exists
' ws = excelApp.ActiveWorkbook.Worksheets(1)
' write text in cell A1
rng = ws.Range("A1")
rng.Formula = "Test123"
' save the workbook in new location
wb.SaveAs(Filename:=Path.Combine(strPathNew, wb.Name), _
FileFormat:=XlFileFormat.xlOpenXMLWorkbook)
excelApp.Quit()
End Sub
End Class
Note: add reference to MS Office Interop for your version of Excel(here example for Excel 2007).

Import text file to new sheet, do some operations, then close the sheet

I have a problem that I need help to solve. I want to import a text file to a new temporary sheet, find some data, put them in my current sheet and then close the new temporary sheet. Is this possible and how do I do this?
To create a new Worksheet, then remove it:
Option Explicit
Sub openWorkSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets.Add(, ThisWorkbook.ActiveSheet)
End Sub
Sub closeWorkSheet(ByRef ws As Worksheet)
If Not ws Is Nothing Then
With Application
.DisplayAlerts = False
ws.Delete
.DisplayAlerts = True
End With
End If
End Sub
To open a text file, read its contents and find specific strings:
Public Sub searchFile(ByVal filePathAndName As String)
Const TYPICAL_START = "FIRST search string"
Const TYPICAL_END = "LAST search string"
Dim fso As Object
Dim searchedFile As Object
Dim fullFile As String
Dim foundStart As Long
Dim foundEnd As Long
Dim resultArr() As String
Dim i As Long
Set fso = CreateObject("Scripting.FileSystemObject")
Set searchedFile = fso.OpenTextFile(filePathAndName)
fullFile = searchedFile.ReadAll 'read entire file
i = 1
foundStart = 1
foundStart = InStr(foundStart, fullFile, TYPICAL_START, vbTextCompare)
If foundStart > 0 Then
foundEnd = InStr(foundStart, fullFile, TYPICAL_END, vbTextCompare)
While foundStart > 0 And foundEnd > 0
ReDim Preserve resultArr(i)
resultArr(i) = Mid(fullFile, foundStart, foundEnd - foundStart + 1)
foundStart = InStr(foundStart + 1, fullFile, TYPICAL_START, vbTextCompare)
If foundStart > 0 Then foundEnd = InStr(foundStart, fullFile, TYPICAL_END)
i = i + 1
Wend
End If
End Sub
So now it shold work. This is the sub that does not want to work.
Sub Import()
Dim DestBook As Workbook, SourceBook As Workbook
Dim DestCell As Range
Dim RetVal As Boolean
' Set object variables for the active book and active cell.
Set DestBook = ActiveWorkbook
Set DestCell = ActiveCell
' Show the Open dialog box.
RetVal = Application.Dialogs(xlDialogOpen).Show("*.txt", , True)
' If Retval is false (Open dialog canceled), exit the procedure.
If RetVal = False Then Exit Sub
' Set an object variable for the workbook containing the text file.
Set SourceBook = ActiveWorkbook
' Copy the contents of the entire sheet containing the text file.
Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)).Copy
' Activate the destination workbook and paste special the values
' from the text file.
DestBook.Activate
DestCell.PasteSpecial Paste:=xlValues
' Close the book containing the text file.
SourceBook.Close False
End Sub

How to Import Data Into Heavy Excel File

Goal
Import about 100+ lines of data into a worksheet. Quickly.
Current Problem
The Excel file isn't very large (not even 1MB). Although, we use this Excel file to communicate with SolidEdge which makes it very heavy.
At the moment, it takes about 60 seconds to populate the 100 lines of data. Don't get me wrong, that isn't very long. Whereas I tested it with a new and empty Excel file and it took less than 1 second to populate the data.
Code
Here's my code incase I did something stupid in there:
Private Sub PopulateExcel()
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim Proceed As Boolean = False
Dim RowIndex As Integer = 2
Dim counter As Integer = 0
xlApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
xlWorkBooks = xlApp.Workbooks
For Each wb As Excel.Workbook In xlWorkBooks
If wb.Name.Contains("301-AAAA-00X") Then
xlWorkBook = wb
xlWorkSheets = xlWorkBook.Sheets
Exit For
End If
Next
If xlWorkSheets IsNot Nothing Then
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = "ImportSheet" Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
End If
If Proceed Then
tspbProgress.Value = 0
tspbProgress.Maximum = dic_Vars.Count
tspbProgress.Visible = True
For Each key As KeyValuePair(Of String, String) In dic_Vars 'Contains all my the data
tsslStatus.Text = "Populating Excel: " & key.Key & " | " & key.Value
xlWorkSheet.Cells(RowIndex, 2).value = key.Key
xlWorkSheet.Cells(RowIndex, 3).value = key.Value
RowIndex += 1
IncProg()
Next
tspbProgress.Visible = False
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If
End Sub
Private Sub ReleaseComObject(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
Conclusion
I was thinking about creating a new Excel file, importing the data there, and just doing a copy / paste to the real Excel file that we use.
Any suggestions?
Good thank you to Byron Wall who helped me find the answer. I now input my data using an array instead of iterating through each cell.
I create my array and populate it depending on how large my dictionary of variables is. I then create a new range using the Resize() method seen below.
Once that's done, everything is populated in an instant!
Dim arrNames(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim arrValues(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim i As Integer = 0
For Each key As KeyValuePair(Of String, String) In dic_Vars
arrNames(i, 0) = key.Key
arrValues(i, 0) = key.Value
i += 1
Next
If Proceed Then
Dim r As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("B2").Resize(arrNames.GetLength(0))
Dim r2 As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("C2").Resize(arrValues.GetLength(0))
r.Value2 = arrNames
r2.Value2 = arrValues
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If