Back to Top

Daily Archives: 2016年3月22日

VB.NET Excelを起動または終了する

VBのプログラムで、Excelを起動または、終了させる方法を記載します。

Shell関数を利用して起動する方法

Dim execPath As String = "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE"
Dim procId As Integer = Shell(execPath, vbNormalFocus)

 

Processクラスを利用して起動する方法

Dim execPath As String = "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE"
Dim execProc As New Process

With execProc
    .StartInfo.FileName = execPath
    .Start()
End With

 

COMオブジェクトを利用して起動および終了する方法

まず参照追加-COMでMicrosoft Excel xxx Object Libraryを追加します。

プログラムにImports Microsoft.Office.Interopを追加します。

'Excel.Applicationのインスタンスを生成する
Dim xlApp As New Excel.Application()

'Excel を表示する
xlApp.Visible = True

'3秒待機する
System.Threading.Thread.Sleep(3000)

'Excel を終了する
xlApp.Quit()

'COM オブジェクトの参照カウントを解放する
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)

 

その他の方法

Dim ExcApp As Object		
ExcApp = CreateObject("Excel.Application")

ExcApp.workbooks.add()
ExcApp.visible = True

 

VB.NET Excelのブックを追加または開く

Excelで、新しいブックを追加する方法および、既存のファイルを開く方法を記載します。

新しいブックを追加してExcelを開きます

Dim xlApp As New Excel.Application()
Dim xlBooks As Excel.Workbooks

'WorkBooksを取得する
xlBooks = xlApp.Workbooks

'新しいブックを追加する
xlBooks.Add()

xlApp.Visible = True

'3秒待機する
System.Threading.Thread.Sleep(3000)

xlApp.Quit()

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)

 

既存のブックをExeclで開きます

Dim xlApp As New Excel.Application()
Dim xlBooks As Excel.Workbooks

'WorkBooksを取得する
xlBooks = xlApp.Workbooks

'既存のブックを開く
xlBooks.Open("C:\work\myBook.xls")

xlApp.Visible = True

'3秒待機する
System.Threading.Thread.Sleep(3000)

xlApp.Quit()

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)