0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Excel VBA]列番号(数値)をアルファベット表記に変換

Last updated at Posted at 2022-12-22

たまに忘れた頃に必要になるので、メモとして残す。

(2022/12/23 追記)

バグっていたので修正。。。

(2022/12/26 追記)

列番号の取り回しの型変更(Long ⇒ Integer)、および、範囲チェック追加

toAlphabet
'アルファベット表記変換
Function toAlphabet(piNumber As Integer) As String

    Const COL_LOWER As Integer = 1
    Const COL_UPPER As Integer = 16384
    Const RADIX     As Integer = 26
    Const CHR_BASE  As Integer = &H40

    Dim iNumber As Integer
    Dim iUpper  As Integer

    toAlphabet = ""
    If (piNumber < COL_LOWER Or piNumber > COL_UPPER) Then
        '範囲外(空文字列を返す)
        Exit Function
    End If

    iNumber = piNumber
    If (piNumber > RADIX) Then
        iUpper = piNumber \ RADIX
        iNumber = piNumber Mod RADIX
        If (iNumber = 0) Then
            iUpper = iUpper - 1
            iNumber = RADIX
        End If
        toAlphabet = toAlphabet(iUpper)
    End If
    toAlphabet = toAlphabet + Chr(iNumber + CHR_BASE)

End Function

なんとなく再帰で作ったけど、もっと単純な方法もありそう。。。

(2023/1/24 追記)

ChatGPT先生 による模範解答

ColumnNumberToName
Function ColumnNumberToName(colNum As Integer) As String
    ColumnNumberToName = ""
    Do While colNum > 0
        colNum = colNum - 1
        ColumnNumberToName = Chr((colNum Mod 26) + 65) & ColumnNumberToName
        colNum = Int(colNum / 26)
    Loop
End Function

ああ、先に -1 してしまうとスッキリするのか。
やっぱり再帰は大袈裟だったか。。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?