Take it easy!

開いているExcelBookとSheetをチェック

by achi on Dec.15, 2008, under VB.NETテクニック

‘開いているExcelBookとSheetをチェック
 ’とりあえずBook名を引数に開いているかどうか
Imports Excel = Microsoft.Office.Interop.Excel
    ‘ExcelOpen検知関数
    ‘Open: fExcelOpen(ExFileName) = True
    Private Function fExcelOpen(ByVal ExFileName As String) As Boolean
        Dim oExcel As Excel.Application
        Dim oBooks As Excel.Workbooks
        Dim oBook As Excel.Workbook
        Dim fsts As Boolean = “False”
        Dim oSheets As Excel.Sheets
        Dim oSheet As Excel.Worksheet
        Try
            ‘別プロセスのExcelを取得する
            ‘GetObjext第1引数のファイルパスは省略する
            oExcel = GetObject(, “Excel.Application”)
            ‘開いているブックを全て取得する
            oBooks = oExcel.Workbooks
            ‘ブック毎に確認
            For Each oBook In oBooks
                If oBook.Name = ExFileName Then
                    fsts = True
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            ‘COMコンポーネントの解放
            If Not oSheet Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet)
                oSheet = Nothing
            End If
            If Not oSheets Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheets)
                oSheets = Nothing
            End If
            ‘COMコンポーネントの解放
            If Not oBook Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
                oBook = Nothing
            End If
            If Not oBooks Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks)
                oBooks = Nothing
            End If
            If Not oExcel Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
                oExcel = Nothing
            End If
        End Try
        Return fsts
    End Function

2 comments for this entry:
  1. KattyBlackyard

    The best information i have found exactly here. Keep going Thank you

  2. Ada

    You made some good points on this subject.

Leave a Reply

*----* Note : *----*
Please write only in Japanese or English.
If you will post any other languages, we'll mark them as spam.

And also if a linked URI in your comments, I do not approve.
*----*----*

You must be logged in to post a comment.