0
1

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 3 years have passed since last update.

エクセルのアドレス形式A:Eを入力するとき列名A,B,C,D,Eを出力する

Posted at

PowerShell とエクセルを連携したいときに時々ほしいやつ。

function New-XlColumnRange {
    param (
        [Parameter(Mandatory=$True)]
        [ValidatePattern("^[a-zA-Z]+:[a-zA-Z]+$")]
        [string]$Address
    )
    $ALPHA = Write-Output A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z

    $S = $Address.Split(":")[0].ToUpper()
    $E = $Address.Split(":")[1].ToUpper()

    # アドレスを一旦数値に戻す
    $toIndex = {
        $ret = 0
        $len = $_.Length
        for($i = 0; $i -lt $len; $i++){
            $n = $ALPHA.indexOf($_[$i]) + 1
            $ret += $n * [Math]::Pow(26, $len - $i - 1)
        }
        return $ret
    }
    $start = $S | ForEach-Object -Process $toIndex
    $end   = $E | ForEach-Object -Process $toIndex

    # 入力チェック
    if ($start -lt 1) { throw 1 }
    if ($end -le $start) { throw 1 }

    # アドレスに戻す
    $toColumn = {
        $ret = ""
        $i = $_
        do {
            $i = $i - 1
            $ret = $ALPHA[$i % 26] + $ret
            $i = [Math]::Floor($i / 26)
        } while ($i -gt 0)
        return $ret
    }

    $start .. $end | ForEach-Object -Process $toColumn
}

例えば以下のような使い方ができる。

$SheetData | Select-Object (New-XlColumnRange "A:D")

$SheetData は適当に用意する。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?