How to move DataGridView row to another DataGridView in another form, with CSV Datasource- VB.net - vb.net

Im using a CSV to load data and save data from the DataGridView I have in a form. I would now like it so with a button click event I can send a row checked via the checkbox column on the DataGridView, to another dataGridView which is hosted in another form.
If it helps, here is the load im using to load and save the DataGridView contents.
Private Sub btnLoadDGVGeneral_Click(sender As Object, e As EventArgs) Handles btnLoadDGVGeneral.Click
' PURPOSE: Load CSV file containing tasks into DataGridView
' Clearing DGV Rows allows for Tasks to not double up when rebooting the program
dataGVGeneral.Rows.Clear()
'New Variable: fname, represents File Path of CSV as String
Dim fname As String = "E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv"
Dim reader As New StreamReader(fname, Encoding.Default)
Dim sline As String = ""
Dim colsexpected As Integer = 7
Dim r As Integer = 0
'StreamReader will the file Line by Line, and add it to the variable sline
'First sline statement is Out of Loop, as first line of CSV contains headings to what each figure represents in a line.
sline = reader.ReadLine
Do
'Now sline will read the 2nd line and so forth
sline = reader.ReadLine
'If no value is found on that line of the CSV file (at the end), then the loop will exit
If sline Is Nothing Then Exit Do
'Details is as a variable, which when called upon, places each value into different columns for that row
Dim details() As String = sline.Split(",")
dataGVGeneral.Rows.Add()
For i As Integer = 0 To 6
dataGVGeneral.Rows(r).Cells(i).Value = details(i)
Next
'Increments value of "r" by 1, meaning next line of CSV will be added to the next row.
Dim v As Integer = r + 1
r = v
Loop
reader.Close()
End Sub
Private Sub btnSaveGeneralDGV_Click(sender As Object, e As EventArgs) Handles btnSaveGeneralDGV.Click
Dim StrExport As String = ""
For Each C As DataGridViewColumn In dataGVGeneral.Columns
StrExport &= """" & C.HeaderText & ""","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
For Each R As DataGridViewRow In dataGVGeneral.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= """" & C.Value.ToString & ""","
Else
StrExport &= """" & "" & ""","
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv", False)
tw.Write(StrExport)
tw.Close()
End Sub

Related

Writing multiple selected DataGridView rows to CSV

The code below successfully allows for me to write a selected row to a .csv file.
I'm having problems where, when I select multiple rows and try and write it to the file, it puts all of the row on the same line of the .csv file.
How can I modify the code below so that it allows for multiple rows to be selected, and it writes each row to a new line of the .csv file?
Dim StrExport As String = ""
For Each C As DataGridViewColumn In dataGVGeneral.Columns
StrExport &= "" & C.HeaderText & ","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
'Only the row which is selected will be written
For Each R As DataGridViewRow In dataGVGeneral.Rows
If R.Selected = True Then
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= "" & C.Value.ToString & ","
Else
StrExport &= "" & "" & ","
End If
Next
Else
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
End If
Next
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\Session.csv", False)
tw.Write(StrExport)
tw.Close()
On the line StrExport = StrExport.Substring(0, StrExport.Length - 1), I think you meant to use &= instead of =.
However, you should be using a StringBuilder to create the string because it is more efficient when concatenating more than about ten pieces of string together.
To join strings together with a comma/anything else between, String.Join is useful because you don't have to worry about the final comma.
And finally, with a little bit of LINQ you can make the code quite a bit shorter but still fairly easy to understand:
Private Sub bnSaveSelected_Click(sender As Object, e As EventArgs) Handles bnSaveSelected.Click
Dim sb As New Text.StringBuilder()
sb.AppendLine(String.Join(",", dataGVGeneral.Columns.Cast(Of DataGridViewColumn).Select(Function(c) c.HeaderText)))
For Each dr As DataGridViewRow In dataGVGeneral.Rows
If dr.Selected Then
sb.AppendLine(String.Join(",", dr.Cells.Cast(Of DataGridViewCell).Select(Function(c) c.Value.ToString())))
End If
Next
IO.File.WriteAllText("C:\temp\SampleCsv.csv", sb.ToString())
End Sub

File can't be accessed because it's already in use

I have a Sub that reads a file that was created in another Sub. I'm getting an error
Can't access file in use in other process
From what I've read on the net I need to close the StreamReader. I've tried to use .close() on different variables, but nothing seems to work.
Below is the code that writes the file the other Sub then accesses.
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
strGraphicFile = MoveLocation & "\ICN-LIST.txt"
Dim ICNFiles = Directory.EnumerateFiles(MovePath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
output.Add(match.Groups(1).Value)
End If
Next
File.WriteAllLines(strGraphicFile, output)
locationGraphicsLog = strGraphicFile
End Sub
The other Sub that reads the file created
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sGraphicFilesToFind As String
Dim graphicLocation As String
'MoveWithPath As String
Dim graphicFile As String
graphicLocation = txtSearchICN.Text
MoveLocation = MovePath
graphicLogFile = MoveLocation & "\Reports\1-OrphanedFilesItems.txt"
Dim FILE_NAME As String
FILE_NAME = MoveLocation & "\ICN-LIST.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sGraphicFile As String
Do While objReader.Peek() <> -1
graphicFile = objReader.ReadLine()
sGraphicFilesToFind = graphicLocation & "\" & graphicFile & "*.*"
sGraphicFile = graphicFile
Dim createGraphicReportFldr As String
Dim paths() As String = IO.Directory.GetFiles(graphicLocation, sGraphicFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
'Debug.Print(graphicFile)
If System.IO.File.Exists(graphicLogFile) = True Then
Dim objWriter As New System.IO.StreamWriter(graphicLogFile, IO.FileMode.Append)
objWriter.WriteLine(graphicFile)
objWriter.Close()
Else
'MsgBox("Creating Orphaned graphicFile Now. ")
createGraphicReportFldr = MoveLocation & "\Reports"
If Not IO.Directory.Exists(createGraphicReportFldr) Then
IO.Directory.CreateDirectory(createGraphicReportFldr)
'MsgBox("folder created" & createGraphicReportFldr)
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(graphicLogFile)
writeFile.Write(graphicFile & vbCrLf)
writeFile.Close()
Else
'MsgBox("Folder already exist")
End If
End If
Else
For Each pathAndFileName As String In paths
Dim createGraphicsFolder As String
'Dim moveFileToNewFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toGraphiicFileLocation As String
'MsgBox("sRegLast " & sRegLast)
fileGraphicLoc = MoveLocation & sRegLast
createGraphicsFolder = MoveLocation & "\Figures"
moveGraphicFileToNewFolder = MoveLocation & "\Figures\" & sRegLast
toGraphiicFileLocation = createGraphicsFolder & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
If Not IO.Directory.Exists(createGraphicsFolder) Then
IO.Directory.CreateDirectory(createGraphicsFolder)
' MsgBox("folder created" & createGraphicsFolder)
End If
If System.IO.File.Exists(fileGraphicLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveGraphicFileToNewFolder)
Debug.Write("Graphics moved to : " & moveGraphicFileToNewFolder & vbCrLf)
End If
End If
Next
End If
Loop
'MsgBox("graphicFiles have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
In the "other Sub", change
Dim objReader As New System.IO.StreamReader(FILE_NAME)
to
Using objReader = New System.IO.StreamReader(FILE_NAME)
and add End Using where you are done with it. Probably right after Loop. This will ensure that the disposable stream is always disposed.
See Using Statement (Visual Basic). You almost always want to wrap an IDisposable object in a Using block if you are able to restrict its scope to a single method.

Only column text appears when csv file is imported to datagridview vb.net

This is my first vb.net program, so please bear with me if my question is very mediocre.
Before mentioning my problem, the mechanism of my accounting program is that if the user would input data into the datagridview and export it, so that when he restarts the program, he can import the exported data.
I have imported this .csv file to my datagridview
The problem is that when I have imported it, only column texts would appear like this.
This is the export code that I have used to create the .csv file.
Private Sub ExportToExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportToExcelToolStripMenuItem.Click
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
Try
Dim iexport1 As String = ""
Dim eexport1 As String = ""
For Each C As DataGridViewColumn In Income.Columns
iexport1 &= """" & C.HeaderText & ""","
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Income.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
iexport1 &= """" & C.Value.ToString & ""","
Else
iexport1 &= """" & "" & ""","
End If
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
Next
For Each C As DataGridViewColumn In Expense.Columns
eexport1 &= """" & C.HeaderText & ""","
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Expense.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
eexport1 &= """" & C.Value.ToString & ""","
Else
eexport1 &= """" & "" & ""","
End If
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
Next
Dim tw As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryIncome.CSV")
tw.Write(iexport1)
tw.Close()
Dim tw2 As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryExpense.CSV")
tw2.Write(eexport1)
tw2.Close()
Catch ex As Exception
End Try
End Sub
And this is the one I have used for importing csv file.
Private Sub ImportFromExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ImportFromExcelToolStripMenuItem.Click
Dim expenseload1 As String = "C:\Users\S2009516\Desktop\JanuaryExpense.CSV"
Dim incomeload1 As String = "C:\Users\S2009516\Desktop\JanuaryIncome.CSV"
Try
Dim expensereader1 As New StreamReader(expenseload1, Encoding.Default)
Dim incomereader1 As New StreamReader(incomeload1, Encoding.Default)
Dim eline As String = ""
Dim iline As String = ""
Do
eline = expensereader1.ReadLine
iline = incomereader1.ReadLine
If eline Is Nothing Then Exit Do
If iline Is Nothing Then Exit Do
Dim words() As String = eline.Split(",")
Dim words2() As String = iline.Split(",")
Income.Rows.Add("")
Expense.Rows.Add("")
For ix As Integer = 0 To 3
Me.Income.Rows(Income.Rows.Count - 1).Cells(ix).Value = words2(ix)
Me.Expense.Rows(Income.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
expensereader1.Close()
incomereader1.Close()
Catch ex As Exception
End Try
End Sub
I have no clue on why this is happening... I have followed all the steps in the tutorial video.. Please save my soul... I have been stuck with this for 2 days already.

How can I export the datagridview to .csv without headers?

My csv file is like this
There is no blank spaces or whatsoever.
The problem as you can see is that I do not know how to export my datagridview as .csv excluding column headers.
This is how I have done my export code:
Private Sub IncomeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles IncomeToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim incomefile As String = String.Empty
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
For Each row As DataGridViewRow In Expense.Rows
For Each cell As DataGridViewCell In row.Cells
incomefile = incomefile & cell.FormattedValue.replace(",", "") & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
Next
System.IO.File.WriteAllText(saveFileDialog1.FileName, incomefile)
End If
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
End Sub
Please advise me. Some others mentioned that I'd better off use datatable to export it, but since I started to learn computer programming 43 hours ago, I have no clue on how to declare the data i have put in my datagridview and export it as csv file.
Remove those lines
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
Give this a try.
Private Sub BtnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport.Click
SFD.InitialDirectory = "C:\"
SFD.Title = "Save Your File"
SFD.Filter = "Microsoft Excel(*.xls)|*.xls|Comma Delimited File(*.csv)|*.Csv"
SFD.OverwritePrompt = True
SFD.ShowDialog()
strFileName = SFD.FileName
' If SFD.ShowDialog() = DialogResult.OK Then
If SFD.FilterIndex = 1 Then
Call export()
Else
Call csv()
End If
' End If
End Sub
Also, try it this way.
Dim numCols As DataGridViewCell
Dim sw As New System.IO.StreamWriter("d:\\output.txt")
For Each numRows As DataGridViewRow In DataGridView1.Rows
Dim intCellCount As Integer = numRows .Cells.Count
Dim intCounter As Integer = 1
For Each numCols In numRows .Cells()
If intCounter <> intCellCount Then
sw.Write(numCols .Value.ToString & ",")
Else
sw.WriteLine(numCols .Value.ToString)
End If
intCounter += 1
Next
Next

Missing Leading Zeros in SQL Export to Excel Loop

New VB programmer here. I am exporting a SQL table to an Excel file using the following method below. However, when I create the file in excel, my leading zeros for my primary key are missing due to being converted to numbers instead of text. This is due to the information coming from the datatable to excel. I am wondering what I can do to keep my leading zeros.
FYI - my primary key is 6 digits with only a few that are missing a single 0 in the beginning of them. There are many other columns and rows that get put into the excel file after the first column which all work perfectly. It is only the first column primary keys which i need to change the format somehow.
Also, I am using this excel file to then upload into SQL and the missing 0 on some of the primary keys maks my program create a new record.
I was thinking the main change could take place here but I cannot figure out how to do so:
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 1
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
Full Code Below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dataAdapter As New SqlClient.SqlDataAdapter()
Dim dataSet As New DataSet
Dim command As New SqlClient.SqlCommand
Dim datatableMain As New System.Data.DataTable()
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "Server=myserver;Database=mydatabase;User Id=xxxx;Password=xxxxx"
command.Connection = connection
command.CommandType = CommandType.Text
'You can use any command select
command.CommandText = "Select * from MYTABLE"
dataAdapter.SelectCommand = command
Dim f As FolderBrowserDialog = New FolderBrowserDialog
Try
If f.ShowDialog() = DialogResult.OK Then
'This section help you if your language is not English.
System.Threading.Thread.CurrentThread.CurrentCulture = _
System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
'Fill data to datatable
connection.Open()
dataAdapter.Fill(datatableMain)
connection.Close()
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 1
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
'Set final path
Dim fileName As String = "\" + fname.Text + ".xlsx"
Dim finalPath = f.SelectedPath + fileName
txtPath.Text = finalPath
oSheet.Columns.AutoFit()
'Save file in final path
oBook.SaveAs(finalPath, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
'Release the objects
ReleaseObject(oSheet)
oBook.Close(False, Type.Missing, Type.Missing)
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
'Some time Office application does not quit after automation:
'so i am calling GC.Collect method.
GC.Collect()
MessageBox.Show("Exported!")
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
End Try
End If
End Sub
Private Sub ReleaseObject(ByVal o As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
End While
Catch
Finally
o = Nothing
End Try
End Sub
I actually just had a similar problem about 10 minutes ago! I needed to get a 30-something digit from one book to another and it was overflowing everything. Try setting the formatting of the column before writing to the cells. My code was Worksheets(i).Range("D:D").NumberFormat = "#" This will tell Excel to interperate the data "as is" instead of trying to guess what you want.
I found this question looking to fix this same issue in a generic function I have, that's used by a couple programs I've created. Due to that variety of data sources I couldn't hard code which columns to set the NumberFormat on. In order to get around it I leveraged the loop I have to output column headers. My code is below for those needing a little more of a dynamic solution. Note, there are a couple references to 'EL' that's an instance of a custom error logging object in the same solution, that can just be ignored/modified:
''' <summary>
''' Function to take a data table and output its contents to an Excel spreadsheet. Returns a string with any errors (Nothing if successful)
''' </summary>
''' <param name="D">The datatable to be output</param>
''' <param name="epath">The full file path to log errors to</param>
''' <param name="SAName">The full file path to save the created Excel workbook to</param>
''' <param name="Parent">The function calling for data to be output</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ResOut(ByVal D As DataTable, ByVal epath As String, ByVal SAName As String, ByVal Parent As String) As String
'
Dim res As String = ""
Dim E As New Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim x As Long = 0
Dim f As Long = 1
Dim Rng As Microsoft.Office.Interop.Excel.Range = Nothing
Dim q As String
Dim Str_Columns As New List(Of String) 'Holds the list of column letters that need forced to Text format in order to retain leading zeroes in the data
'that will be placed there
'Check that the passed in table has data
If D.Rows.Count = 0 Then
res = "No data was returned by " & Parent
End If
If res = "" Then
'Create a workbook for the data and capture the workbook and sheet for ease of reference
Try
wb = E.Workbooks.Add
ws = wb.Worksheets(1)
'Define the range
q = ColNumToStr(D.Columns.Count, epath)
Rng = ws.Range("A2:" & q & D.Rows.Count + 1)
Catch ex As Exception
res = "Encountered an error while creating the new workbook to export the results to. No data can be returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
'Fill in headers
If res = "" Then
Try
For Each c As DataColumn In D.Columns
ws.Range("A1").Offset(0, x).Value = c.ColumnName
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while filling in the column headers. This will prevent any data from being returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'Setup the step & frequency for the Step Progress bar
'Dim t() As Long = s.StatSetup(QR.Rows.Count, 58, "Query Runner\ResOut\" & QName, Replace(My.Settings.EPath, "<user>", Environment.UserName) & DStamp() & " Query Scheduler Log.txt")
'f = t(0)
'SProg.Step = t(1)
'Create the array
Dim OArr(D.Rows.Count, x) As Object
'Convert the datatable to a 2D array
If res = "" Then
Try
'Fill it
x = 0
For r As Long = 0 To D.Rows.Count - 1 Step 1
Dim dr As DataRow = D.Rows(r)
For c As Integer = 0 To D.Columns.Count - 1 Step 1
OArr(r, c) = dr.Item(c).ToString
'Check if this item is a # with leading zeroes (making sure we haven't already added the column to the list of such columns)
If Not (Str_Columns.Contains(ColNumToStr(c + 1, epath))) And Strings.Left(dr.Item(c), 1) = "0" Then
Str_Columns.Add(ColNumToStr(c + 1, epath))
End If 'else the column is in the list already or the item does not dictate it's inclusion
Next
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while outputing the " & x + 1 & "-th record of " & D.Rows.Count & ". No data will be output."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'output the array to the target range
If res = "" Then
'First force Text format where needed to retain leading zeroes
Try
For Each c As String In Str_Columns
q = c
ws.Range(c & ":" & c).NumberFormat = "#"
Next
Catch ex As Exception
res = "Encountered an error while changing column " & q & " to TEXT in order to retain leading zeroes in the " & ws.Range(q & 1).Value & "data."
E.Visible = True
wb.Activate()
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message & Chr(10) & Chr(10) & "Inner Exception: " & ex.InnerException.Message _
, epath)
End Try
Try
Rng.Value = OArr
'Save the workbook
wb.SaveAs(SAName)
wb.Close(SaveChanges:=False)
Catch ex As Exception
res = "Encountered an error during the export of the results. Some data may have been exported. Review the contents of the Excel workbook that will " _
& "be visible following this message for more details."
E.Visible = True
wb.Activate()
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
Else
'Close the workbook without saving
wb.Close(SaveChanges:=False)
End If
'Cleanup the application
Try
E.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(E)
E = Nothing
wb = Nothing
ws = Nothing
Rng = Nothing
OArr = Nothing
f = Nothing
x = Nothing
Catch ex As Exception
EL.AddErr("Encountered an error while cleaning up the resources used in JMLib\ResOut. ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
Return res
End Function