Imports Excel = Microsoft.Office.Interop.Excel
Module Module1
Sub Main()
Dim filePath As String = "C:\path\to\your\file.xlsx"
Dim data As Object(,) = ReadExcelToArray(filePath)
' 配列の内容を出力 (例)
If data IsNot Nothing Then
Dim rows As Integer = data.GetLength(0)
Dim cols As Integer = data.GetLength(1)
For i As Integer = 1 To rows
For j As Integer = 1 To cols
Console.Write(data(i, j) & vbTab)
Next
Console.WriteLine()
Next
End If
End Sub
Function ReadExcelToArray(ByVal filePath As String) As Object(,)
Dim excelApp As New Excel.Application
Dim workbook As Excel.Workbook = Nothing
Dim worksheet As Excel.Worksheet = Nothing
Dim range As Excel.Range = Nothing
Dim data As Object(,)
Try
' Excelを開く
workbook = excelApp.Workbooks.Open(filePath)
worksheet = workbook.Sheets(1) ' 1つ目のシートを取得
range = worksheet.UsedRange ' 使用されている範囲を取得
' 範囲を2次元配列として取得
data = range.Value
Catch ex As Exception
Console.WriteLine("エラー: " & ex.Message)
Finally
' 後片付け
If Not workbook Is Nothing Then workbook.Close(False)
excelApp.Quit()
ReleaseObject(range)
ReleaseObject(worksheet)
ReleaseObject(workbook)
ReleaseObject(excelApp)
End Try
Return data
End Function
' COMオブジェクトを解放する関数
Private Sub ReleaseObject(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
Finally
GC.Collect()
End Try
End Sub
End Module