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?

Power Automate Desktopで行・列インデックスからアドレス文字列を取得する

0
Posted at

概要

Power Automate DesktopでExcel操作をしていると、「行インデックス」「列インデックス」から A1 形式のセルアドレス文字列を作りたい場面が稀にあります。

例えば、

  • 列=1、行=1 → A1
  • 列=28、行=3 → AB3

といったように、列番号(1始まり)を Excel の列名(A, B, …, Z, AA, AB…)へ変換し、行番号と連結するケースです。PAD 標準アクションだけでも近いことはできますが、列番号 → 列名の変換処理はやや面倒になりがちです。

本記事では、「.NET スクリプト実行(VB.NET)」アクションを利用して、シンプルに一発変換する方法を紹介します。

実装概要

「.NET スクリプト実行」アクションを使用し、言語には「VB.NET」を指定します。
本実装では、以下を行います。

  1. 列インデックス(数値)を Excel の列名(A~Z、AA~)に変換
  2. 行インデックスを文字列として連結
  3. A1 形式のセルアドレス文字列を生成して出力
' colIndex(1始まり)と rowIndex(1始まり)から "A1" 形式を生成する
' 例: (1,1)->A1 / (28,3)->AB3 / (27,1)->AA

Dim dividend As Integer = colIndex
Dim columnName As String = ""

While dividend > 0
    ' 末尾の1文字(A~Z)を求める(Excel列は 1始まりなので -1 して調整
    Dim modulo As Integer = (dividend - 1) Mod 26
    
    ' 65="A" のASCIIコード。前に連結して右→左に列名を組み立てる    
    columnName = Convert.ToChar(65 + modulo).ToString() & columnName
    
    ' 次の桁へ(整数除算)    
    dividend = (dividend - 1) \ 26
End While

' 列名 + 行番号で A1 形式にする
outCellAddress = columnName & rowIndex.ToString()

スクリプトパラメーター設定

以下のように 入力値(In)と出力値(Out)を設定します。

入力値(In)

  • colIndex

  • rowIndex

出力値(Out)

  • outCellAddress

まとめ

Excel の列番号 → 列名変換は、毎回やろうとすると意外と面倒な処理のひとつです。
PAD 標準アクションで頑張るより、.NET スクリプトでサクッと文字列を作ってしまう方がシンプルなケースも多いと思います。

ちょっとした Excel 操作の部品として、参考になれば幸いです。

補足:アドレス文字列から行・列インデックスを取得する

逆に、"AB3" のような A1形式のセルアドレス文字列から、列インデックス(1始まり) と 行インデックス(1始まり) を取り出したいこともあります。

例えば以下のように変換できます。

  • A1 → 列=1、行=1
  • Z10 → 列=26、行=10
  • AB3 → 列=28、行=3

やっていることはシンプルで、文字列を先頭から1文字ずつ見ていき、

  • 英字(A~Z)なら列番号へ反映(26進数として加算)
  • 数字(0~9)なら行番号へ反映(10進数として加算)

という手順で計算します。

' cellAddress(例: "AB3")から、列・行インデックス(どちらも1始まり)を取り出す
' outColIndex: 列番号(A=1, Z=26, AA=27 ...)
' outRowIndex: 行番号(1, 2, 3 ...)

Dim outColIndex As Integer = 0
Dim outRowIndex As Integer = 0

' 前後空白を除去し、大文字化してから1文字ずつ処理する
For Each ch As Char In cellAddress.Trim().ToUpper()

    If System.Char.IsLetter(ch) Then
        ' 英字部分(列名)を 26進数的に変換する
        ' 例: "AB" = (0*26+1)*26+2 = 28
        ' 64 は "A"=65 のため、(ch - 64) で A=1 ... Z=26 にする
        outColIndex = outColIndex * 26 + (System.Convert.ToInt32(ch) - 64)

    ElseIf System.Char.IsDigit(ch) Then
        ' 数字部分(行番号)を 10進数として組み立てる
        ' 例: "12" = 0*10+1 -> 1*10+2 -> 12
        outRowIndex = outRowIndex * 10 + System.Convert.ToInt32(ch.ToString())
    End If

Next
0
0
1

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?