AccessVBA

VBAでエクセルの書式を設定する

投稿日:


動画で楽にパソコンが身につく方法はこちら>>

VBAでエクセルの書式を設定するには、エクセルオブジェクトを利用します。
以下はエクセルの書式を設定するプログラムの一例です。

Dim oApp As Object
Set oApp = CreateObject(“Excel.Application”)
Dim xlRange As Excel.Range
Dim objBook ‘ExcelBook
Dim objSheet

‘指定のエクセルファイルを開く
oApp.Workbooks.Open filename:=pas & filename

Set objBook = oApp.ActiveWorkbook

‘エクセルファイルへデータセットする
oApp.Sheets(“日計表”).Select
Set objSheet = objBook.Sheets(1)

‘中央揃え
oApp.Range(“C” & Format(i + 2)).HorizontalAlignment = xlHAlignCenter
oApp.Range(“C” & Format(i + 3)).HorizontalAlignment = xlHAlignCenter
oApp.Range(“C” & Format(i + 4)).HorizontalAlignment = xlHAlignCenter

HorizontalAlignmentで水平方向、xlHAlignCenterで中央揃えという意味です。

xlHAlignRightは右揃えになります。

‘セルの結合
oApp.Range(“C” & Format(i + 1) & “:D” & Format(i + 1)).MergeCells = True

oApp.Range(“セル範囲”).MergeCells = True

MergeCells = Trueでセルを結合します。

‘文字サイズフィット
oApp.Range(“C” & Format(i + 4) & “:D” & Format(i + 4)).ShrinkToFit = True

oApp.Range(“セル範囲”).ShrinkToFit = True

.ShrinkToFit = Trueで文字をセル幅を文字にそろえなさいという意味になります。

‘罫線全体内容
Set xlRange = oApp.Range(“A” & Format(st) & “:O” & Format(i – 1))
xlRange.Borders(xlEdgeTop).LineStyle = xlDouble
xlRange.Borders(xlEdgeLeft).LineStyle = xlContinuous
xlRange.Borders(xlInsideVertical).LineStyle = xlContinuous
xlRange.Borders(xlInsideHorizontal).LineStyle = xlDot
xlRange.Borders(xlEdgeRight).LineStyle = xlContinuous
xlRange.Borders(xlEdgeBottom).LineStyle = xlContinuous

ここではセルに罫線を引きます。

Set xlRange = oApp.Range(“セル範囲”)でまず罫線を引く範囲を設定します。

次にそれぞれの罫線の位置と種類を設定します。

xlRange.Borders(xlEdgeTop).LineStyle = xlDoubleの場合、

xlEdgeTopはセルの上端、xlEdgeLeftは左端、xlEdgeRightは右端、

xlEdgeBottomはセルの底辺、xlInsideVerticalはセルとセルの境界線(垂直方向)

xlInsideHorizontalはセルとセルの境界線(水平方向)になります。

.LineStyle = xlDouble で線の種類を指定できます。

xlDoubleで二重線、xlContinuousで直線、xlDotで点線となります。

‘カンマ
oApp.Columns(“D”).Style = “Comma [0]”

ここではセルDの列にカンマ区切りを設定します。

Columns(“D”)でD列、.Style = “Comma [0]”でカンマ区切りの設定です。

Set xlRange = Nothing
oApp.Workbooks(1).Close SaveChanges:=True
oApp.Quit
Set oApp = Nothing

エクセルオブジェクトの終了、開放をします。


動画で楽にパソコンが身につく方法はこちら>>

-AccessVBA

Copyright© エクセルVBA使い方入門 , 2023 All Rights Reserved Powered by STINGER.