1

I'm currently struggling with the following problem

I'm trying to implement an input box where a user can input the character of the column.

After that, i dont know how to convert this into a number to use it in the Worksheet.Cells Method

For example: The User inputs "B", so the program saves it in a variable named x and converts it into a number so it can be used as Worksheet.Cells(Row, X)

Is there any method or does someone has an idea how to do this?

brettdj
  • 54,857
  • 16
  • 114
  • 177
ndslr
  • 47
  • 2
  • 8

3 Answers3

7

Cells() is your friend.

Don't overthink this.

Cells(1, 1) = "jello" ' changes cell A1
Cells(2, "AZ") = "too much jello" ' changes cell AZ2

The second argument of Cells() can be either a number or the alpha column header.

teylyn
  • 34,374
  • 4
  • 53
  • 73
0

B is the second column, so you can use the expression (based on ASCII):

Sub main()
    Dim s As String
    s = "AB"
    example s
End Sub

Sub example(s As String)

    Dim colNum As Integer
    Dim i As Integer

    i = 1: colNum = 0
    While (Mid(s, i, 1) <> "")
        colNum = colNum * 26 + (Asc(UCase(Mid(s, i, 1))) - Asc("A") + 1)
        i = i + 1
    Wend
    MsgBox colNum
End Sub
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • I was about to suggest this myself, but a problem occurs once you move past column Z: `?Asc(lcase("aa"))-asc("a")+1` in the immediate-window outputs 1. – eirikdaude Feb 10 '16 at 07:51
0
Function getColNum(colLetter As String) As Long
    On Error Resume Next   'will return 0 if letter > last col
    getColNum = Range(colLetter & "1").Column
End Function
iDevlop
  • 24,841
  • 11
  • 90
  • 149