3

数値を対応する MS Excel ヘッダー値に変換するロジックを実行する際に助けが必要です。

例えば:

1 = "A" 2 = "B" 3 = "C" 4 = "D" 5 = "E" .... 25 = "Y" 26 = "Z" 27 = "AA" 28 = "AB" 29 = "AC" 30 = "AD" ..........

これには、いくつかの .NET コード (C# または VB) をいただければ幸いです。ありがとう。

4

5 に答える 5

1

これは、トリックを行うExcelでつなぎ合わせたVBA(テストコード付き)です。VB.NET が大幅に変更されていない限り、問題なく動作するはずです。たとえそれがあったとしても、そのアイデアを実行可能なコードに変換できるはずです。

' num2col - translate Excel column number (1-n) into column string ("A"-"ZZ"). '

Function num2col(num As Integer) As String
    ' Subtract one to make modulo/divide cleaner. '

    num = num - 1

    ' Select return value based on invalid/one-char/two-char input. '

    If num < 0 Or num >= 27 * 26 Then
        ' Return special sentinel value if out of range. '

        num2col = "-"
    Else
        ' Single char, just get the letter. '

        If num < 26 Then
            num2col = Chr(num + 65)
        Else
           ' Double char, get letters based on integer divide and modulus. '

           num2col = Chr(num \ 26 + 64) + Chr(num Mod 26 + 65)
        End If
    End If
End Function

 

' Test code in Excel VBA. '

Sub main()
    MsgBox ("-  should be " & num2col(0))
    MsgBox ("A  should be " & num2col(1))
    MsgBox ("B  should be " & num2col(2))
    MsgBox ("Z  should be " & num2col(26))
    MsgBox ("AA should be " & num2col(27))
    MsgBox ("AB should be " & num2col(28))
    MsgBox ("AY should be " & num2col(51))
    MsgBox ("AZ should be " & num2col(52))
    MsgBox ("BA should be " & num2col(53))
    MsgBox ("ZY should be " & num2col(27 * 26 - 1))
    MsgBox ("ZZ should be " & num2col(27 * 26))
    MsgBox ("-  should be " & num2col(27 * 26 + 1))
End Sub
于 2009-08-13T03:56:07.560 に答える
0
public string ColumnNumberToLetter(int ColumnNumber)
{
    if (ColumnNumber > 26)
    {
        return ((char) (Math.Floor(((double)ColumnNumber - 1) / 26) + 64)).ToString()
               + ((char) (((ColumnNumber - 1) % 26) + 65)).ToString();
    }
    return ((char)(ColumnNumber+64)).ToString();
}
于 2009-08-13T03:56:56.683 に答える
-1

基数変換ルーチンを使用します。基数 10 から基数 26 に変換します。各桁を「A」に追加します

のように: http://www.vbforums.com/showthread.php?t=271359

于 2009-08-13T04:00:15.180 に答える
-1

activecell.address を使用するだけで、$ が必要な場所に基づいて文字列を操作できます。

于 2009-10-02T04:25:34.653 に答える