Create excel ranges using column numbers in vba?

前端 未结 9 2109
误落风尘
误落风尘 2021-02-02 05:56

How is it possible to create a range in vba using the column number, rather than letter?

9条回答
  •  情歌与酒
    2021-02-02 06:14

    I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.

    I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).

    Function ConvertToLetter2(iCol As Integer) As String
        Dim First As Integer
        Dim Second As Integer
        Dim FirstChar As String
        Dim SecondChar As String
    
        First = Int(iCol / 26)
        If First = iCol / 26 Then
            First = First - 1
        End If
        If First = 0 Then
            FirstChar = ""
        Else
            FirstChar = Chr(First + 64)
        End If
    
        Second = iCol Mod 26
        If Second = 0 Then
            SecondChar = Chr(26 + 64)
        Else
            SecondChar = Chr(Second + 64)
        End If
    
        ConvertToLetter2 = FirstChar & SecondChar
    
    End Function
    

提交回复
热议问题