Create excel ranges using column numbers in vba?

前端 未结 9 2112
误落风尘
误落风尘 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:21

    These answers seem strangely convoluted. Unless I'm missing something...if you want to convert numbers to letters, you can just stock them all in an array using a for loop then call on the number associated with that column letter. Like so

    For intloop = 1 To 26
        colcheck(intloop) = Chr$(64 + intloop)
        For lenloop = 1 To 26
            colcheck((intloop * 26) + lenloop) = Chr$(64 + intloop) & Chr$(64 + lenloop)
            For terloop = 1 To 26
                colcheck((intloop * 676) + (lenloop * 26) + terloop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop)
                For qualoop = 1 To 26
                    colcheck((intloop * 17576) + (lenloop * 676) + (terloop * 26) + qualoop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop) & Chr$(64 + qualoop)
                Next qualoop
            Next terloop
        Next lenloop
    Next intloop
    

    Then just use colcheck(yourcolumnnumberhere) and you will get the column heading associated with that letter (i.e. colcheck(703) = AAA

    0 讨论(0)
  • 2021-02-02 06:24

    Here is a condensed replacement for the ConvertToLetter function that in theory should work for all possible positive integers. For example, 1412 produces "BBH" as the result.

    Public Function ColumnNumToStr(ColNum As Integer) As String
    Dim Value As Integer
    Dim Rtn As String
        Rtn = ""
        Value = ColNum - 1
        While Value > 25
            Rtn = Chr(65 + (Value Mod 26)) & Rtn
            Value = Fix(Value / 26) - 1
        Wend
        Rtn = Chr(65 + Value) & Rtn
        ColumnNumToStr = Rtn
    End Function
    
    0 讨论(0)
  • 2021-02-02 06:24

    Haha, Lovely - let me also include my version of stackPusher's code :). We are using this functionality in C#. Works fine for all Excel ranges.:

    public static String ConvertToLiteral(int number)
    {
            int firstLetter = (((number - 27) / (26 * 26))) % 26;
            int middleLetter = ((((number - 1) / 26)) % 26);
    
            int lastLetter = (number % 26);
            firstLetter = firstLetter == 0 ? 26 : firstLetter;
            middleLetter = middleLetter == 0 ? 26 : middleLetter;
            lastLetter = lastLetter == 0 ? 26 : lastLetter;
            String returnedString = "";
            returnedString = number > 27 * 26 ? (Convert.ToChar(firstLetter + 64).ToString()) : returnedString;
            returnedString += number > 26 ? (Convert.ToChar(middleLetter + 64).ToString()) : returnedString;
            returnedString += lastLetter >= 0 ? (Convert.ToChar(lastLetter + 64).ToString()) : returnedString;
            return returnedString;
    }
    
    0 讨论(0)
提交回复
热议问题