如何从Excel列字母中获取列号(或索引)

时间:2013-07-23 18:37:44

标签: excel function character

我搜索了这个网站并搜索了一个公式。我需要从字母计算Excel列号,例如:

A=1
B=2
..
AA=27
AZ=52
...
AAA=703

在字母表的随机循环(AZ - > BA == off digit)之后,代码似乎是1位数。它似乎也会从两个不同的输入中随机产生相同的整数:

GetColumnNumber(xlLetter : Text) : Integer //Start of function

 StringLength := STRLEN(xlLetter);
 FOR i := 1 TO StringLength DO BEGIN
 Letter := xlLetter[i];
   IF i>1 THEN
     Count += ((xlLetter[i-1]-64) * (i-1) * 26) - 1;
   Count += (Letter - 64);
 END;
 EXIT(Count); //return value

我的代码示例是用C / AL编写的,用于动态数据库,但我也可以编写C#或vb.net,所以我不介意一个例子是否使用这两种语言。

3 个答案:

答案 0 :(得分:3)

在VBA中:

Public Function GetCol(c As String) As Long
    Dim i As Long, t As Long
    c = UCase(c)
    For i = Len(c) To 1 Step -1
        t = t + ((Asc(Mid(c, i, 1)) - 64) * (26 ^ (Len(c) - i)))
    Next i
    GetCol = t
End Function

答案 1 :(得分:3)

在VBA中:

Function ColLetter(C As Integer) As String
  If C < 27 Then
    ColLetter = Chr(64 + C)
  Else
    ColLetter = ColLetter((C - 1) \ 26) & ColLetter((C - 1) Mod 26 + 1)
  End If
End Function

答案 2 :(得分:0)

在VBA中:(递归函数)

    Function Get_Col_Number(strColName As String, dRunningNo As Integer) As Double
        Dim dCurrentColNo As Double
        Dim dMultipleValue As Double

        strColName = Ucase(strColName)

        If (dRunningNo <= 0) Then Get_Col_Number = 0:   Exit Function

        dCurrentColNo = ((Asc(Mid(strColName, dRunningNo, 1)) - Asc("A") + 1))
        dMultipleValue = 26 ^ (Len(strColName) - dRunningNo)

        Get_Col_Number = (dCurrentColNo * dMultipleValue) + Get_Col_Number(strColName, (dRunningNo - 1))
    End Function

使用此功能如下。

Sub Main()
    Dim StrGetNoForThisColumnName As String
    StrGetNoForThisColumnName = "Xfd"

    Msgbox "Final Result : " & Get_Col_Number(StrGetNoForThisColumnName, Len(StrGetNoForThisColumnName))
End Sub