VBA列數字與字母互換

<內容來至Excelhome>


vba列數字與字母互換:


方案一:速度:快


Function NumToStr(ByVal Num As Long) As String   '數字轉字母
    Dim M As Long
    If Num < 1 Then Exit Function
    Do
        M = Num Mod 26
        If M = 0 Then M = 26
        NumToStr = Chr(64 + M) & NumToStr
        Num = (Num - M) / 26
    Loop Until Num <= 0
End Function




Function StrToNum(ByVal Str As String) As Long '字母轉數字
    Dim s As String, S1 As String
    If Str = "" Then Exit Function
    Str = UCase(Str)
    s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    For i = 1 To Len(Str)
        S1 = Mid(Str, i, 1)
        If InStr(s, S1) = 0 Then Crazy_Num = -1: Exit Function
        StrToNum = StrToNum + InStr(s, S1) * 26 ^ (Len(Str) - i)
    Next
End Function
方案二:迭代 速度:略快 


Function colinf(t) '列標籤字母⇔列序號數值 相互轉換
    If t = "" Then colinf = "": Exit Function '如果引用単元格=空白 即返回空白退出
    If IsNumeric(t) Then '如果引用単元格=數值(列序號),計算返回列標籤大寫英文字母
        If t < 1 Then colinf = "": Exit Function '如果數是0或負數返回空白退出
        Do
            colinf = Chr((t - 1) Mod 26 + 65) & colinf '以26除數反複Mod求餘得到1-26字母
            t = Int((t - 1) / 26) '求餘後再用26除後Int取整……
        Loop Until t <= 0 '反複迭代計算直至數t已不能除26求餘止
    Else '如果引用単元格=文本字符,計算返回序號數値
        t = UCase(t) '首先文本転換大寫字母
        For i = 1 To Len(t) '遍各字符
            colinf = colinf + (Asc(Mid(t, i, 1)) - 64) * 26 ^ (Len(t) - i) '按26冪乗計算累計數
        Next
    End If
End Function




方案三:遞歸 速度:略快 


Function getColStr$(n) '列序號數字→列標籤字母
    Dim s$, t as long
    t = n
    Do
        s = Chr((t - 1) Mod 26 + 65) & s
        t = Int((t - 1) / 26)
    Loop Until t <= 0
    getColStr = s
End Function


方案四:


Function getC_Str(n) '列序號數字→列標籤字母


    getC_Str = Split(Cells(1, n).Address, "$")(1)


End Function


------------------以下爲測試3種方案全碼-----------------
Sub test()
    dqT = Timer
    M = 1000: n = 10000
    Dim strTmp


    For i = 1 To M
        For j = 1 To n
            strTmp = getC_Str(n)
        Next j
    Next i


    dqT1 = Timer
    For i = 1 To M
        For j = 1 To n
            strTmp = getColStr(j)
        Next j
    Next i
    dqT2 = Timer


    For i = 1 To M
        For j = 1 To n
            strTmp = NumToStr(n)
        Next j
    Next i


    MsgBox " getC_Str  用時:" & Format(Timer - dqT1, "0.0000") & vbLf & "getColStr 用時:" & Format(dqT2 - dqT1, "0.0000") & vbLf & "NumToStr用時:" & Format(Timer - dqT2, "0.0000")
End Sub


Function getColStr$(n) '列序號數字→列標籤字母
     Dim s$, t as long
    t = n
    Do
        s = Chr((t - 1) Mod 26 + 65) & s
        t = Int((t - 1) / 26)
    Loop Until t <= 0
    getColStr = s
End Function


Function NumToStr(ByVal Num As Long) As String   '數字轉字母
    Dim M As Long
    If Num < 1 Then Exit Function
    Do
        M = Num Mod 26
        If M = 0 Then M = 26
        NumToStr = Chr(64 + M) & NumToStr
        Num = (Num - M) / 26
    Loop Until Num <= 0
End Function


Function getC_Str(n) '列序號數字→列標籤字母


    getC_Str = Split(Cells(1, n).Address, "$")(1)


End Function
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章