- 題名: VBから、EXCELのシートをCOPY/DELETEすることができますか
- 日時: 2005/06/24 13:35:58
- ID: 11457
- この記事の返信元:
- (なし)
- この記事への返信:
- [11462] Re[1]: VBから、EXCELのシートをCOPY/DELETEすることができますか2005/06/24 17:04:21
- ツリーを表示
こんにちは、じゃんぬ と申します。
■No11457に返信(johnさんの記事)
> VBから、EXCELのシートをCOPY/DELETEすることができますか?
> 次のコードは、削除することが、うまくいかないです。教えてください。
それ以前にこのコードでは Excel のオブジェクトが解放されません。
参照したオブジェクトを変数に渡していないので、解放する術をもちません。
解放は、System.Runtime.InteropServices.Marshal.ReleaseComObject メソッドでやってください。
' 必要な変数は Try の外で宣言する
Dim xlApp As Excel.Application
Dim xlBooks As Excel.Workbooks
Dim xlBook As Excel.Workbook
Dim xlSheets As Excel.Sheets
Dim xlSheet As Excel.Worksheet
Try ' 必要な変数は Try の中でインスタンス化する
xlApp = New Excel.Application()
xlBooks = xlApp.Workbooks
xlBook = xlBooks.Open("C:\NakaHirotoshi.xls")
xlSheets = xlBook.Worksheets
' Microsoft Excel を表示する
xlApp.Visible = True
' シートのカウントが 1 より大きければシートを削除する
If xlSheets.Count > 1 Then
' Display アラートがうざいので消す
xlApp.DisplayAlerts = False
' シートを削除する
xlSheet = DirectCast(xlSheets(1), Excel.Worksheet)
xlSheet.Delete()
xlApp.DisplayAlerts = True
End If
' 1000 ミリ秒 (1秒) 待機する
System.Threading.Thread.Sleep(1000)
' Excel ブックを保存する
xlBook.Save()
' Microsoft Excel を終了する
xlApp.Quit()
Finally
' 参照したオブジェクトをすべて解放する
If Not xlSheet Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
End If
If Not xlSheets Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets)
End If
If Not xlBook Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
End If
If Not xlBooks Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
End If
If Not xlApp Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
End If
End Try
本当は、Try 〜 Finally を変数ごとに入れ子にしないといけませんが、面倒なので省きました。
また Delete() メソッドは共有ブックだと失敗します。(Exception を Throw する)
分類:[.NET]
VBから、EXCELのシートをCOPY/DELETEすることができますか?
次のコードは、削除することが、うまくいかないです。教えてください。
Dim ExcelObj As New Excel.Application
Dim wBOOK As Excel.Workbook
Dim wsheet As Excel.Worksheet
wBOOK = ExcelObj.Workbooks.Open("C:\text.xls")
wsheet = wBOOK.Sheets(1)
wsheet.Delete()
wBOOK.Save()
wBOOK.Close()
wsheet = Nothing
wBOOK = Nothing