VBA Finding the next column based on an input value

后端 未结 5 1434
隐瞒了意图╮
隐瞒了意图╮ 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:23

    You were on the right track with Offset. Here is a test function that shows a couple different approaches to take with it:

    Sub test()
    
    Dim first_Column As String
    Dim second_Column As String
    Dim third_Column As String
    Dim r As Range
    
        first_Column = Range("B2").Text
        second_Column = Range("B2").Offset(1, 0).Text
        third_Column = Range("B2").Offset(2, 0).Text
        Debug.Print first_Column, second_Column, third_Column
    
        Set r = Range("B2")
        first_Column = r.Text
        Set r = r.Offset(1, 0)
        second_Column = r.Text
        Set r = r.Offset(1, 0)
        third_Column = r.Text
        Debug.Print first_Column, second_Column, third_Column
    
    End Sub
    

    UPDATE: After re-reading your question I realize you were trying to do offsets based on a user-entered column letter. @rskar's answer will shift the column letter, but it will be a lot easier to work with the column number in code. For example:

    Sub test()
    Dim first_Col As Integer, second_Col As Integer
        first_Col = Cells(, Range("B2").Text).Column
        second_Col = first_Col + 1
    
        Cells.Columns(first_Col).Font.Bold = True
        Cells.Columns(second_Col).Font.Italic = True
    End Sub
    

提交回复
热议问题