How is it possible to create a range in vba using the column number, rather than letter?
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
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
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;
}