-------------------------------------------------------------------------
(3)生成したExcelデータの体裁を整える
<要望>
Excelレポートを生成した後、列の幅や、外枠の設定、背景色の設定を行うのは面倒。レポート生成時に自動で設定されるようにしたい。
<レポートの設定内容>
Excelレポートの[後処理]タブにて、VBAをコーディングします。
この例では、UsedRangeプロパティを使用することで生成したデータのみを選択し、その範囲に罫線を引いています。
<VBA>
---------------------------------------------------------------------
Sub QC_PostProcessing()
Dim MainWorksheet As Worksheet
' Make sure your worksheet name matches!
Set MainWorksheet = ActiveWorkbook.Worksheets("Sheet1")
Dim DataRange As Range
Set DataRange = MainWorksheet.UsedRange
' Now that you have the data in DataRange you can process it.
' --------------- ここから ------------------
Cells.Select
Cells.EntireColumn.AutoFit
DataRange.Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
Range("A1").Select
' --------------- ここまで ------------------
End Sub
---------------------------------------------------------------------
<注意>
Excelレポートの[後処理]では、予め元になるスクリプトが挿入されています。プロシージャ名やレンジ指定などは変更しないようにしてください。
<補足>
新しくVBAを作成する場合、Excelで[ツール]→[マクロ]の順にクリックし、[新しいマクロの記録]で罫線を引く操作を記録します。
[Visual Basic Editor]で記録したマクロをコピーし、Excelレポートの[後処理]タブに貼り付けるだけで、簡単に[後処理]のVBAを作成することが出来ます。