VBA Finding the next column based on an input value

后端 未结 5 1438
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 21:56

In a program that I\'m trying to write now I take two columns of numbers and perform calculations on them. I don\'t know where these two columns are located until the user tell

5条回答
  •  春和景丽
    2021-01-27 22:34

    Here are two functions that will help you dealing with columns > "Z". They convert the textual form of a column to a column index (as a Long value) and vice versa:

    Function ColTextToInt(ByVal col As String) As Long
        Dim c1 As String, c2 As String
        col = UCase(col) 'Make sure we are dealing with "A", not with "a"
        If Len(col) = 1 Then  'if "A" to "Z" is given, there is just one letter to decode
            ColTextToInt = Asc(col) - Asc("A") + 1
        ElseIf Len(col) = 2 Then
            c1 = Left(col, 1)  ' two letter columns: split to left and right letter
            c2 = Right(col, 1)
            ' calculate the column indexes from both letters  
            ColTextToInt = (Asc(c1) - Asc("A") + 1) * 26 + (Asc(c2) - Asc("A") + 1)
        Else
            ColTextToInt = 0
        End If
    End Function
    
    Function ColIntToText(ByVal col As Long) As String
        Dim i1 As Long, i2 As Long
        i1 = (col - 1) \ 26   ' col - 1 =i1*26+i2 : this calculates i1 and i2 from col 
        i2 = (col - 1) Mod 26
        ColIntToText = Chr(Asc("A") + i2)  ' if i1 is 0, this is the column from "A" to "Z"
        If i1 > 0 Then 'in this case, i1 represents the first letter of the two-letter columns
            ColIntToText = Chr(Asc("A") + i1 - 1) & ColIntToText ' add the first letter to the result
        End If
    End Function
    

    Now your problem can be solved easily, for example

    newColumn = ColIntToText(ColTextToInt(oldColumn)+1)
    

    EDITED accordingly to the remark of mwolfe02:

    Of course, if you are not interested in the column names, but just want to get a range object of a specific cell in a given row right beneath a column given by the user, this code is "overkill". In this case, a simple

     Dim r as Range
     Dim row as long, oldColumn as String
     ' ... init row and oldColumn here ...
    
     Set r = mysheet.Range(oldColumn & row).Offset(0,1)
     ' now use r to manipulate the cell right to the original cell
    

    will do it.

提交回复
热议问题