VB.NET Error in import Excel in datagrid view - vb.net

I have this code in a button to import excel (which I got online as well)
Imports System.Data
Imports Microsoft.Office.Interop
Public Class Template
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xlRange As Excel.Range
Dim sFileName As String
Dim xlRow As Integer
With OpenFileDialog1
.Title = "Import Excel"
.FileName = ""
.Filter = "Excel File|*.xlsx;*.xls"
If .ShowDialog() = DialogResult.OK Then
sFileName = .FileName
If Trim(sFileName) <> "" Then
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open(sFileName)
xlWorkSheet = xlWorkBook.Worksheets("Template")
xlRange = xlWorkSheet.UsedRange
Dim rowcount As Integer = 17
For xlRow = 17 To xlRange.Rows.Count '//data starts at R17C1
If xlRange.Cells(xlRow, 1).Text <> String.Empty Then
rowcount += 1
DataGridView1.Rows.Add(rowcount, xlRange.Cells(xlRow, 1).Text,
xlRange.Cells(xlRow, 2).Text,
xlRange.Cells(xlRow, 3).Text,
xlRange.Cells(xlRow, 4).Text,
xlRange.Cells(xlRow, 5).Text,
xlRange.Cells(xlRow, 6).Text,
xlRange.Cells(xlRow, 7).Text,
xlRange.Cells(xlRow, 8).Text,
xlRange.Cells(xlRow, 9).Text,
xlRange.Cells(xlRow, 10).Text)
End If
Next
End If
End If
End With
End Class
Now I am having an error System.MissingMemberException:
I am stuck for days and no solution has been found online. I tried using .ToString instead of .Text but it only I got System_.Comobject displayed in datagrid. I have the correct path and sheet name. Please help me solve this error. I am pretty new with .Net so guide and treat me as a beginner.

I have found a solution for my question. I used the code below and it worked.
DataGridView1.Rows.Add(xlRange.Range("A" & xlRow.ToString).Text, ...)

Related

How can i read excel sheet's text boxes using vb.net (trying to automate a process using uipath invoke code activity)

I'm trying to get the values from Excel TextBoxes using VB.NET, but everything goes wrong. (errors like:" 'Forms' is not a member of Interop " OR "TextBos is not an Interface")
Any Ideas?
Here is my code:
Dim xlApp As Application
Dim xlWorkBooks As Workbooks
Dim xlWorkBook As Workbook
Dim xlWorkSheet As Worksheet
Dim xlWorkSheets As Sheets
Using Microsoft.Vbe.Interop.Forms.TextBox
Dim tb As Forms.TextBox
xlApp = New Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open("C:\Users\pw02318\Documents\UiPath\Accese\exemplu_formular.xlsm")
'xlApp.Visible = True
xlWorkSheets = xlWorkBook.Sheets
xlWorkSheet = CType(xlWorkSheets("New Form"), Worksheet)
For Each shp As Shape In xlWorkSheet.Shapes
Dim oo As OLEObject = CType(xlWorkSheet.OLEObjects(shp.Name), OLEObject)
tb = CType(oo.Object, Microsoft.Vbe.Interop.Forms.TextBox)
console.WriteLine(oo.Name.ToString + tb.Text)
Next shp
End Using
You can read your excel file and put it in a data reader using ExcelDataReader.
first add OpenXml.Excel.Data to your references and import it in your code, then you can write as below:
logDestination = Environment.CurrentDirectory & "\log.txt"
Dim filePaths As String() = Directory.GetFiles(path, "*.xlsx")
If filePaths.Length > 1 Then
File.AppendAllText(logDestination, DateTime.Now & " -----> There Is More Than One xlsx File In The Path Folder" + Environment.NewLine)
ElseIf filePaths.Length = 0 Then
File.AppendAllText(logDestination, DateTime.Now & " -----> There Is No xlsx File In The Path" + Environment.NewLine)
Environment.[Exit](0)
End If
Dim dt = New DataTable()
Dim reader As var = New ExcelDataReader(filePaths(0), 1, True)
dt.Load(reader)

Copying Datagridview to excel - leaves excel process open

Can anyone point out what is causing the excel process to remain open after my code finishes?
I've researched everything on this topic and the main point seems to be to avoid 3 dots with excel interop, but I believe I have done that and I still can't see where I'm going wrong.
my process is to copy the datagridview to the clipboard and then paste it in a newly created excel file, save it, close excel, and then give the user an option to open the file.
Two scenarios. First, when I run through the code and DON'T open the excel file it leaves the process open. Second, if I open the workbook and then close the workbook it doesn't leave a process running. I don't understand the difference because the opening of the workbook happens after I try to close and release all references to excel.
Private Sub CopyDGVtoClipBoard()
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
Me.DataGridView1.RowHeadersVisible = False
Me.DataGridView1.SelectAll()
Dim dataObj As DataObject = Me.DataGridView1.GetClipboardContent
If dataObj IsNot Nothing Then
Clipboard.SetDataObject(dataObj)
End If
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText
Me.DataGridView1.RowHeadersVisible = True
Me.DataGridView1.ClearSelection()
End Sub
Private Sub ExportToExcel()
If Me.DataGridView1.Rows.Count < 1 Then Exit Sub
CopyDGVtoClipBoard()
SaveFileDialog1.Filter = "Excel File|*.xlsx"
SaveFileDialog1.Title = "Save In"
SaveFileDialog1.FileName = "Generic name"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If SaveFileDialog1.FileName <> "" Then
Dim xlExcel As excel.Application
Dim xlWorkBooks As excel.Workbooks
Dim xlWorkBook As excel.Workbook
Dim xlWorkSheet As excel.Worksheet
Dim CR As excel.Range
Dim misValue As Object = System.Reflection.Missing.Value
xlExcel = New excel.Application
xlExcel.Visible = True
xlWorkBooks = xlExcel.Workbooks
xlWorkBook = xlWorkBooks.Add(misValue)
xlWorkBook.Application.DisplayAlerts = False
xlWorkSheet = xlWorkBook.ActiveSheet
CR = xlWorkSheet.Cells(1, 1)
CR.Select()
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True)
xlWorkBook.SaveAs(SaveFileDialog1.FileName())
xlWorkBook.Close(False)
misValue = Nothing
ReleaseExcel(CR)
ReleaseExcel(xlWorkSheet)
ReleaseExcel(xlWorkBook)
ReleaseExcel(xlWorkBooks)
xlExcel.Quit()
ReleaseExcel(xlExcel)
Dim OpenCheck As MsgBoxResult = MsgBox("Would you like to open the file?", MsgBoxStyle.YesNo, "Open File")
Dim fPath As String = SaveFileDialog1.FileName
If OpenCheck = MsgBoxResult.Yes Then
Process.Start(fPath)
End If
End If
End If
Private Sub ReleaseExcel(ByVal O As Object)
Do While System.Runtime.InteropServices.Marshal.ReleaseComObject(O) >= 0
System.Runtime.InteropServices.Marshal.ReleaseComObject(O)
Loop
O = Nothing
End Sub
I've narrowed the issue down to the below code. If I do everything except specifying a range and adding data it'll close and end the process but as soon as I reference CR = xlWorkSheet.Cells(1,1) it hangs a process
CR = xlWorkSheet.Cells(1, 1)
CR.Select()
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True)
Edit
So I compared my code vs. what Karen posted and made some slight adjustments to my code (full code plus changes listed below), but for some reason it works and doesn't leave a process open! Not sure how, but I'll take it.
Private Sub CopyDGVtoClipBoard()
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
Me.DataGridView1.RowHeadersVisible = False
Me.DataGridView1.SelectAll()
Dim dataObj As DataObject = Me.DataGridView1.GetClipboardContent
If dataObj IsNot Nothing Then
Clipboard.SetDataObject(dataObj)
End If
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText
Me.DataGridView1.RowHeadersVisible = True
Me.DataGridView1.ClearSelection()
End Sub
Private Sub ExportToExcel()
If Me.DataGridView1.Rows.Count < 1 Then Exit Sub
CopyDGVtoClipBoard()
Dim DateCon As DateTime = DateTime.ParseExact(Today.ToShortDateString, "M/d/yyyy", Nothing)
SaveFileDialog1.Filter = "Excel File|*.xlsx"
SaveFileDialog1.Title = "Save In"
SaveFileDialog1.FileName = "Generic Name"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If SaveFileDialog1.FileName <> "" Then
Dim xlExcel As excel.Application = Nothing
Dim xlWorkBooks As excel.Workbooks = Nothing
Dim xlWorkBook As excel.Workbook = Nothing
Dim xlWorkSheet As excel.Worksheet = Nothing
Dim CR As excel.Range = Nothing
Dim misValue As Object = System.Reflection.Missing.Value
xlExcel = New excel.Application
xlExcel.Visible = False
xlExcel.DisplayAlerts = False
xlWorkBooks = xlExcel.Workbooks
xlWorkBook = xlWorkBooks.Add(misValue)
xlWorkSheet = xlWorkBook.ActiveSheet
CR = xlWorkSheet.Range("A1")
CR.PasteSpecial(excel.XlPasteType.xlPasteAll)
CR.Select()
xlWorkBook.SaveAs(SaveFileDialog1.FileName)
Clipboard.Clear()
ReleaseExcel(CR)
CR = Nothing
ReleaseExcel(xlWorkSheet)
xlWorkSheet = Nothing
xlWorkBook.Close(False)
ReleaseExcel(xlWorkBook)
xlWorkBook = Nothing
ReleaseExcel(xlWorkBooks)
xlWorkBooks = Nothing
xlExcel.Quit()
ReleaseExcel(xlExcel)
xlExcel = Nothing
Dim OpenCheck As MsgBoxResult = MsgBox("Would you like to open the file?", MsgBoxStyle.YesNo, "Open File")
Dim fPath As String = SaveFileDialog1.FileName
If OpenCheck = MsgBoxResult.Yes Then
Process.Start(fPath)
End If
End If
End If
End Sub
Private Sub ReleaseExcel(ByVal O As Object)
Try
Do Until System.Runtime.InteropServices.Marshal.FinalReleaseComObject(O) = 0
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(O)
Loop
Catch ex As Exception
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
The following goes along with using only two dots. After the work is done excel is properly disposed of.
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module Demo1
Public Sub DoPaste()
Dim FileName As String = IO.Path.Combine(Application.StartupPath, "SomeFile.xlsx")
Dim SheetName As String = "Sheet1"
Dim Proceed As Boolean = False
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 xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Dim xlRange1 As Excel.Range = Nothing
xlRange1 = xlWorkSheet.Range("A1:B6")
xlRange1.Select()
xlRange1.Copy()
Dim xlDestination As Excel.Range = Nothing
xlDestination = xlWorkSheet.Range("C1:D6")
xlDestination.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone)
Marshal.FinalReleaseComObject(xlDestination)
xlDestination = Nothing
Marshal.FinalReleaseComObject(xlRange1)
xlRange1 = Nothing
xlWorkSheet.SaveAs(FileName)
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Exit For
End If
Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module

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

Exported excel file from datagridview shows error when opened VB

I'm doing an export in VB. I was able to export the values of the datagridview to excel but when I open the file, it shows this error.
I'm using the following code to export the values of the datagridview.
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim sPath As String = String.Empty
Dim dlgSave As New SaveFileDialog
Dim i As Integer
Dim j As Integer
dlgSave.DefaultExt = "xls"
dlgSave.Filter = "Microsoft Excel|*.xls"
If dlgSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To dgvFile.RowCount - 1
For j = 0 To dgvFile.ColumnCount - 1
For k As Integer = 1 To dgvFile.Columns.Count
xlWorkSheet.Cells(1, k) = dgvFile.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = dgvFile(j, i).Value.ToString()
Next
Next
Next
Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", ".xlx")
xlWorkSheet.SaveAs(sFilename)
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Dim res As MsgBoxResult
res = MsgBox("Process completed, Would you like to open file?", MsgBoxStyle.YesNo)
If (res = MsgBoxResult.Yes) Then
Process.Start(sFileName)
End If
End If
NOTE
This code works fine. It exports the values without any problem. It just shows the error when I open the excel file. The exported file has no problem when I click "Yes". It shows the correct values. I just want this error to stop showing when I open the file.
Can anyone help me fix this solution? I will be truly grateful to anyone who can lead me. Thanks. :)
I figured it out. Thanks to akhil kumar.
My Excel uses .xlsx extension so I changed
dlgSave.DefaultExt = "xls"
to
dlgSave.DefaultExt = "xlsx"
and removed the Replace function to make it look like this.
Dim sFileName As String = dlgSave.FileName
This works perfectly. This problem was sorted. :)

Manipulating Excel files using VB8

My script is pulling some information (filename, date, &c) from a server that contains only (nearly) identical excel files generated by a separate application whenever it is used. The goal is to find out who is using the tool and how often.
I need help with two things: extracting info from within the excel file, and appending the results to the SAME excel file each time it's run instead of creating a new file each time.
Here is what I have...
Imports Excel = Microsoft.Office.Interop.Excel Imports System Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'declare excel objects
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer = 2
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = " File Name "
xlWorkSheet.Cells(1, 2) = " Date Created "
'this should be cell B1
xlWorkSheet.Cells(1, 3) = " Requestor "
'this should be cell B21
xlWorkSheet.Cells(1, 4) = " Lead Type"
'get to directory
For Each strFolder As String In _
My.Computer.FileSystem.GetDirectories("Z:\\...")
'get file names
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(strFolder)
'write to excel worksheet
xlWorkSheet.Cells(i, 1) = strFolder
xlWorkSheet.Cells(i, 2) = infoReader.CreationTime
i += 1
Next
xlWorkSheet.SaveAs("C:\...")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , see file in c:\Documents")
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
Instead of creating a new application and workbook, just use activeworkbook, e.g.
replace
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
with
xlWorkBook = xlApp.ActiveWorkbook
xlWorkSheet = xlWorkBook.Sheets("sheetname")
where you replace sheetname with whatever the desired sheet name is.
Alternatively, you could just use ActiveSheet.