VBAで先頭の0埋めを実施する(001、002、…、100)

こんてんつ

VBAで先頭を0埋めするコードを記載する。以下の3つの例を紹介する。

  1. MsgBoxに「001、002、…、010」と書き込む例
  2. テキストファイル(001.txt、002.txt、…、010.txt)を作成し、"Hello 001! "、"Hello 002! "、…、"Hello 010!" と書き込む例
  3. セルに「001、002、…、010」と入れていく例

地味に、最後の「セルに入れる」が難しい。

MsgBoxに「001、002、…、010」と書き込む例

  • Format(i, "000")で、iの書式を"000"の桁数にする
  • Right("000" & i, 3)で、0とiをつなげた文字列の右から3文字を抜き出す

入力

Sub Test1_1()

Dim i As Long
Dim j As String
Dim msg As String

For i = 1 To 10

j = Format(i, "000")
msg = msg & j
msg = msg & ", "

Next i

MsgBox msg

End Sub
Sub Test1_2()

Dim i As Long
Dim j As String
Dim msg As String

For i = 1 To 10

j = Right("000" & i, 3)
msg = msg & j
msg = msg & ", "

Next i

MsgBox msg

End Sub

出力

f:id:norunblog:20210808174929p:plain

テキストファイル(001.txt…)を作成し、"Hello 001! "… と書き込む例

入力

Sub Test2()

Dim i As Long
Dim j As String

Dim fsoOBJ As FileSystemObject
Set fsoOBJ = New FileSystemObject

For i = 1 To 10

j = Format(i, "000")
fsoOBJ.CreateTextFile(ThisWorkbook.Path & "\" & j & ".txt").WriteLine ("Hello " & j & "!")

Next i

End Sub

出力

f:id:norunblog:20210808180950p:plain

FileSystemObject、CreateTextFileについては下記の記事を参考に。

contents-open.hatenablog.com

セルに「001、002、…、100」と入れていく例

.NumberFormatLocalによってセルの書式を変更する必要がある。後ろの「@」が文字列の意味を表す。これをやらないと0埋めできない。

入力

Sub Test3()

Dim i As Long
Dim j As String

For i = 1 To 10

j = Format(i, "000")
Cells(i, 1).NumberFormatLocal = "@"
Cells(i, 1).Value = j

Next i

End Sub

出力

f:id:norunblog:20210808182308p:plain