VBA エディタ(VBE)には、Visual Studio のようなコードの自動整形機能がありません。
引き継いだマクロのインデントがバラバラで読めなかったので、整形処理を自作しました。そのときに「ここは考慮が必要だった」というポイントをまとめます。
最後に、ポイントを押さえた Python の簡易版(約60行)も載せています。
基本方針:行単位で「深さ」を数える
VBA は If ~ End If、For ~ Next のように、ブロックの始まりと終わりがキーワードで決まります。
1行ずつ見て、
- ブロックを開く行(
Sub・If ... Then・For・Do・With・Select Caseなど)を出力したら、深さを +1 - ブロックを閉じる行(
End Sub・End If・Next・Loop・End Withなど)は、深さを -1 してから出力 -
途中の行(
Else・ElseIf)は、深さを1つ戻した位置に出力(深さは変えない)
とするのが基本です。ここまでは素直ですが、VBA には例外がいくつかあります。
考慮が必要だったポイント
1. 文字列とコメントの中のキーワード
MsgBox "Then を押してください" ' ここで End If しない
文字列やコメントの中の Then や End If に反応しないよう、判定用に文字列の中身とコメントを取り除いた行を別に作ります。
' は文字列の中にも現れる(例:"It's")ので、先に文字列を消してからコメントを切るのがポイントです。""(エスケープされた引用符)も、"[^"]*" で文字列を消せば自然に処理できます。
2. 1行 If はブロックを開かない
If i = 50 Then Debug.Print "半分" ' End If は来ない
Then の後ろに処理が続く1行 If は、ブロックになりません。判定用の行が Then で終わるときだけブロックを開きます。
3. Select Case は2段
Select Case x
Case 1
処理
Case Else
処理
End Select
Case 行は Select Case より1段深く、その中身はさらに1段深くなります。
2つ目以降の Case は「前の Case の中身」を閉じてから出力し、End Select では2段分戻します。ただし Case が1つもない Select Case もあり得るので、Case が出てきたかどうかを覚えておきます。
4. 行継続( _)
MsgBox "マイナス: " & _
i
行末が _ の行の次は、1段深くして出力します。続きの行はブロックの判定に使わない(深さを変えない)のが安全です。
5. ラベルは行頭に
ErrHandler:
MsgBox Err.Description
On Error GoTo ErrHandler の飛び先などのラベルは、VBE でも行頭に置くのが一般的です。名前: だけの行はインデントせず行頭に出します。
6. 条件付きコンパイル(#If)
#If VBA7 Then
Dim p As LongPtr
#Else
Dim p As Long
#End If
#If ~ #End If も、通常の If と同じようにブロックとして扱えます。
Python の簡易版
上のポイントを入れた簡易版です(Type・Enum・Property などにも対応、空行はそのまま)。
import re
INDENT = " "
# 文字列リテラルとコメントを取り除いて、キーワード判定だけに使う
def strip_code(line: str) -> str:
s = re.sub(r'"[^"]*"', '""', line) # 文字列の中身を空にする(' や Then が入っていても誤判定しない)
s = s.split("'", 1)[0].strip() # コメントを取り除く
return "" if re.match(r"(?i)rem\b", s) else s
OPEN = re.compile(r"(?i)^((public|private|friend)\s+)?(static\s+)?(sub|function|property)\b"
r"|^(public\s+|private\s+)?(type|enum)\b"
r"|^(for|do|while|with|select\s+case)\b"
r"|^#if\b")
CLOSE = re.compile(r"(?i)^end\s+(sub|function|property|type|enum|with|select|if)\b"
r"|^(next|loop|wend)\b|^#end\s+if\b")
MIDDLE = re.compile(r"(?i)^(else|elseif\b.*|#else|#elseif\b.*)$|^(else|#else)\b")
LABEL = re.compile(r"^[A-Za-z_]\w*:$|^\d+$")
def format_vba(src: str) -> str:
out, level, cont, select_depth = [], 0, False, []
for raw in src.splitlines():
line = raw.strip()
code = strip_code(line)
if not line:
out.append("")
continue
if cont: # 行継続の続きは1段深く
out.append(INDENT * (level + 1) + line)
cont = code.endswith(" _")
continue
if LABEL.match(code): # エラー処理のラベルなどは行頭に
out.append(line)
continue
low = code.lower()
if CLOSE.match(code):
level -= 1
if low.startswith("end select") and select_depth.pop():
level -= 1 # Case があれば、その分も戻す
out.append(INDENT * level + line)
elif MIDDLE.match(code):
out.append(INDENT * (level - 1) + line)
elif low.startswith("case ") and select_depth:
if select_depth[-1]: # 2つ目以降の Case は1段戻ってから
level -= 1
out.append(INDENT * level + line)
select_depth[-1] = True
level += 1
else:
out.append(INDENT * level + line)
# 1行 If(Then の後ろに処理がある)はブロックを開かない
block_if = re.match(r"(?i)^(if|#if)\b.*\bthen$", code) is not None
if block_if or (OPEN.match(code) and not low.startswith("#if")):
level += 1
if low.startswith("select case"):
select_depth.append(False)
cont = code.endswith(" _")
return "\n".join(out)
実行結果
整形前:
Sub 集計()
Dim i As Long
For i = 2 To 100
If Cells(i, 3).Value > 0 Then
Select Case Cells(i, 2).Value
Case "A"
Cells(i, 5).Value = "優先"
Case Else
Cells(i, 5).Value = "通常"
End Select
ElseIf Cells(i, 3).Value < 0 Then
MsgBox "マイナス: " & _
i
Else
If i = 50 Then Debug.Print "半分"
End If
Next i
Exit Sub
ErrHandler:
MsgBox Err.Description
End Sub
整形後:
Sub 集計()
Dim i As Long
For i = 2 To 100
If Cells(i, 3).Value > 0 Then
Select Case Cells(i, 2).Value
Case "A"
Cells(i, 5).Value = "優先"
Case Else
Cells(i, 5).Value = "通常"
End Select
ElseIf Cells(i, 3).Value < 0 Then
MsgBox "マイナス: " & _
i
Else
If i = 50 Then Debug.Print "半分"
End If
Next i
Exit Sub
ErrHandler:
MsgBox Err.Description
End Sub
この簡易版で対応していないもの
-
If a > 0 And _のように行継続して、続きの行がThenで終わる If(行継続をつなげてから判定する必要がある) - 1行に
:で複数の文を書いたもの(For i = 1 To 3: x = x + i: Next) -
Exit Subの後ろの不要な空行の整理、行末の空白の削除
実用的には、このあたりにも対応が必要です。
インデントを整えたいマクロ入りのブックがたくさんある場合のために、ブックやフォルダを選ぶだけで VBA を一括整形するツールも作っています。
- VBA整形くん(BOOTH):https://hodoki.booth.pm/items/8952543