VB.NETでExcelを操作するその1
参照設定でMicrosoft Excel xx.x object libraryを参照設定は不要
但しoExcel = CreateObject(“Excel.Application”)だが64ビット版は
oExcel = CreateObject(“Excel.Application.15”) 2016,2019なら.16
使い方はMS本家の「オブジェクトモデル (Excel)」
https://docs.microsoft.com/ja-jp/office/vba/api/overview/excel/object-model
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim wk_filename As String = "c:\work\test1.xlsx"
Dim oExcel As Object = Nothing
Dim xlBook As Object = Nothing
Dim xlSheet As Object = Nothing
Try
'起動していればそのExcelを使用します
oExcel = GetObject(, "Excel.Application.15")
Catch ex As Exception
'Excel が起動していないなら新規にインスタンスを生成します
oExcel = CreateObject("Excel.Application.15")
End Try
oExcel.Visible = True
xlBook = oExcel.Workbooks.Open(wk_filename)
xlSheet = xlBook.Sheets(“sheet1”)
' MsgBox(xlSheet.Range(“B2”).Value)
’
’xlSheet.Cells(1, 1).Value = "APP_Name"’
oExcel.UserControl = True
MRComObject(xlSheet)
MRComObject(xlBook)
' oExcel.Quit()
MRComObject(oExcel)
'xlSheet = Nothing
'xlBook = Nothing
'oExcel = Nothing
End Sub
Private Sub MRComObject(ByVal objCom As Object) '
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(objCom)
Catch ex As Exception
objCom = Nothing
Finally
objCom = Nothing
End Try
End Sub
End Class