【解決方法】こんにちは、Excel から Visual Studio VB にデータをインポートしようとしています。 しかし、データをインポートしているときに、値の代わりに {system.__comobject} を取得しました! ! !

プログラミングQA


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

私が試したこと:

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!!!

解決策 1

電話すると Cells オブジェクトを返します: Worksheet.Range プロパティ (Microsoft.Office.Tools.Excel) | Microsoft Docs[^] したがって、DGV で直接使用すると、暗黙的な ToString 呼び出しが行われ、型の名前が返されます。 System.__ComObject

セルのコンテンツが必要な場合は、その Value プロパティを使用して取得します。

VB
xlRange.Cells(xlRow, 1).Value

解決策 2

同様の問題がありましたが、機能するコードは

xlRange.Value2(xlRow, 1))

範囲の後に「セル」をドロップし、Value または Value2 に直接移動します。

コメント

タイトルとURLをコピーしました