Back to Top

Daily Archives: 2016年3月23日

VB.NET Excelのシートを追加する

Excelのブックに、シートを追加する方法を記載します。

シートを1つ追加する

Dim xlApp As Excel.Application = New Excel.Application()

xlApp.Workbooks.Open("C:\work\myBook.xls")

----------------------------------------------------------------------
Dim NewSheet As Excel.Worksheet = xlApp.Worksheets.Add()
NewSheet.Name = "シート1"

または

With xlApp.Worksheets.Add()
    .Name = "シート1"
End With
----------------------------------------------------------------------

xlApp.Visible = True

System.Threading.Thread.Sleep(3000)

xlApp.Quit()

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

 

シートを複数追加する

xlSheets.Add(Before, After, Count, Type)
'Before:ここで指定したシートの前に新規シートが追加されます。
'After :ここで指定したシートの後ろに新規シートが追加されます。
'Count :追加するシート数です。
'Type  :追加するタイプを指定します。通常(WorkSheet)
Dim xlApp As Excel.Application = New Excel.Application()

xlApp.Workbooks.Open("C:\work\myBook.xls")

Dim xlSheet As Excel.Worksheet = DirectCast(xlApp.Worksheets(1), Excel.Worksheet)   ' 1シート目を選択

'指定シート(xlSheet)の後ろに2つ追加します。
xlApp.Worksheets.Add(, xlSheet, 2, Excel.XlSheetType.xlWorksheet)

xlApp.Visible = True

System.Threading.Thread.Sleep(3000)

xlApp.Quit()

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

 

 

VB.NET Excelシートのセルの値および属性を変更する

Excelでシート内のセルの値および属性を変更する方法を説明します。

変更にはRangeを使用して変更します。そのため1つのセルだけでわなく複数のセルを一度に変更することができます。

セル値およびセルの属性の設定をする

Dim xlApp As Excel.Application
Dim xlSheet As Excel.Worksheet

xlApp = New Excel.Application()

xlApp.Application.Workbooks.Add()
xlSheet = CType(xlApp.Worksheets(1), Excel.Worksheet)
xlSheet.Name = "シート"


' セル選択(単一・複数指定できる)
Dim xlCells As Excel.Range = xlSheet.Range("C3")
または
Dim xlCells As Excel.Range = xlSheet.Cells.Range("C3")
または
Dim xlCells As Excel.Range = xlSheet.Cells(3, 3)


' セルのフォント設定
xlCells.Font.Size = 20
xlCells.Font.Name = "MS 明朝"

' セルにデータ書込み
xlCells.Value = "1234567890"

' セルの背景色設定
xlCells.Interior.Color = &H44FFFF

' セルの文字色設定
xlCells.Font.Color = &HFFFF00


xlApp.Visible = True

System.Threading.Thread.Sleep(3000)
xlApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)