Back to Top

Monthly Archives: 3月 2016

VB.NET Excelのシートをプリンタ印刷する

Excelファイルをプリンタに印刷する方法を記載します。

シートをプリンタに印刷する

Dim xlApp As Excel.Application = New Excel.Application()
Dim xlBook As Excel.Workbook = xlApp.Workbooks.Open("C:\work\myBook.xls")
Dim xlSheet As Excel.Worksheet = xlBook.Worksheets("Sheet1")

'ヘッダー、フッターの記入
With xlSheet.PageSetup
    .Orientation = Excel.XlPageOrientation.xlLandscape
    .CenterHeader = "&12&B" & " ヘッダータイトル " & "&12&B&U"
    .RightHeader = Now().Year & "年" & Now.Month & "月" & Now.Day & "日"
    .CenterFooter = "&P / &N ページ"
    .Zoom = 100
End With

xlApp.Application.DisplayAlerts = False

--------------------------------------------------------------------
'ファイルをセーブする

xlBook.SaveAs(Filename:="C:\work\myBook4.xls", FileFormat:=Excel.XlFileFormat.xlExcel8)  'ファイルに保存

--------------------------------------------------------------------
'プリンタに印刷する

xlSheet.PrintOut()

--------------------------------------------------------------------
'プレビューサイズを指定する

'Dim xlWindow = xlApp.ActiveWindow
'xlWindow.View = Excel.XlWindowView.xlPageBreakPreview
'xlSheet.PageSetup.Zoom = 100
'xlWindow.Zoom = 75

--------------------------------------------------------------------
'印刷プレビューを表示する
xlSheet.Activate()
xlApp.Visible = True
xlSheet.PrintPreview()

--------------------------------------------------------------------

xlBook.Close()
xlApp.Application.DisplayAlerts = True
xlApp.Quit()

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)

 

VB.NET フォルダを削除する

フォルダごとフォルダ内のファイル、サブフォルダ、を削除する方法を記載します。

Directoryクラスを使用する方法

Dim sPath As String = "C:\work"

'フォルダを削除する
System.IO.Directory.Delete(sPath)

'サブフォルダ・ファイル全て削除する
'読み取り専用ファイルがあるとエラーとなる(中途半端に消される)
System.IO.Directory.Delete(sPath, True)

 

DeleteDirectory メソッドを使用する方法

Dim sPath As String = "C:\work"

'フォルダを削除する
My.Computer.FileSystem.DeleteDirectory(sPath, FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)

'サブフォルダ・ファイル全て削除する
My.Computer.FileSystem.DeleteDirectory(sPath, FileIO.DeleteDirectoryOption.DeleteAllContents)

 

DirectoryInfo クラスを使用する方法

Dim sPath As String = "C:\work"

Dim finfo As New System.IO.DirectoryInfo(sPath)

'フォルダを削除する
finfo.Delete()

'内部のサブフォルダも削除する
finfo.Delete(True)