Click here to Skip to main content
14,934,560 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Imports Microsoft.Office.Interop
Public Class Form1
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim xlRange As Excel.Range
        Dim xlRow As Integer
        Dim strFilename As String
        Dim V As String
        'Dim data(0 To 100) As String
        With OpenFileDialog1
            .Filter = "Excel Office| *.xls;* .xlsx"
            .ShowDialog()
            strFilename = .FileName
        End With

        If strFilename <> String.Empty Then
            xlApp = New Excel.Application
            xlWorkBook = xlApp.Workbooks.Open(strFilename)
            xlWorkSheet = xlWorkBook.Worksheets("sheet1")
            xlRange = xlWorkSheet.UsedRange
            For xlRow = 2 To xlRange.Rows.Count
                V = DataGridView1.Rows.Add(xlRange.Cells(xlRow, 1),
                                               xlRange.Cells(xlRow, 2),
                                               xlRange.Cells(xlRow, 3),
                                               xlRange.Cells(xlRow, 4))

            Next
            xlWorkBook.Close()
            xlApp.Quit()

        End If
    End Sub

End Class


What I have tried:

Hi, I'm trying to import data from Excel to Visual Studio VB. But when I'm  importing the data I got {System.__ComObject} instead of Values!!!
Posted
Updated 1-May-21 1:29am
Comments
Richard MacCutchan 1-May-21 6:33am
   
The cell reference returns a COM object. You need to use the Value property to get the contents.
Dr. Ali Yahya Gheni 1-May-21 6:47am
   
Please can you help me to revise the code above? with many thanks

1 solution

When you call Cells it returns an object: Worksheet.Range Property (Microsoft.Office.Tools.Excel) | Microsoft Docs[^] So if you use it directly into a DGV, it will get an implicit ToString call - which returns the name of the type: System.__ComObject

If you want the cell content, then use it's Value property to get it:
VB
xlRange.Cells(xlRow, 1).Value
   
Comments
Dr. Ali Yahya Gheni 1-May-21 8:13am
   
Not working 😑
Ralf Meier 1-May-21 15:54pm
   
... and what happens ?
Which result do you get ?
Dr. Ali Yahya Gheni 2-May-21 0:59am
   
Now it's working..thanks 🌺

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900