VBScript で Excel

Excel ファイルを 作成する

lesson006.vbs


Dim objExcel
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False '警告メッセージをOFF

'ブックを読み取り専用で開く
Dim bookIn
Set bookIn = objExcel.Workbooks.Open(WScript.Arguments(0))

'ブックを書き込み用で開く
Dim bookOut
Set bookOut = objExcel.Workbooks.Add

'いったん、シートを1枚だけにする
Dim iSheet
For iSheet = bookOut.WorkSheets.Count To 2 Step -1
bookOut.WorkSheets(iSheet).Delete
Next

For iSheet = 1 To bookIn.WorkSheets.Count
'必要なら、シートを追加する
If iSheet > bookOut.WorkSheets.Count Then
bookOut.Sheets.Add , bookOut.WorkSheets(iSheet - 1)
End If

Dim sheetIn: Set sheetIn = bookIn.WorkSheets(iSheet)
Dim sheetOut: Set sheetOut = bookOut.WorkSheets(iSheet)

'シート名を変更する
If sheetOut.Name <> sheetIn.Name Then
sheetOut.Name = sheetIn.Name
End If

'データをコピーする
Dim iRow
For iRow = 1 To sheetIn.Cells.CurrentRegion.Rows.Count
Dim iCol
For iCol = 1 To sheetIn.Cells.CurrentRegion.Columns.Count
sheetOut.Cells(iRow, iCol).Value = sheetIn.Cells(iRow, iCol).Value
Next
Next
Next

'ブックを保存する
bookOut.SaveAs(WScript.Arguments(1))

objExcel.Quit
Set objExcel = Nothing

実行結果

C:\>cscript c:\study\vbscript\chapter004\lesson006.vbs c:\study\Book1.xls c:\stu
dy\Book2.xls //nologo