Home » excel » excel – VBA getting the column number from the Target in a worksheet change

excel – VBA getting the column number from the Target in a worksheet change

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a table of values that I need to fill out through a worksheet change function.
What I am trying to do is change a cell in columns B-G, depending on where the target is.

Private Sub Worksheet_Change(ByVal Target As Range)
If (Not Intersect(Target, Range(Cells(12, 2), Cells(14, 7))) Is Nothing) Then
    Cells(16,Application.WorksheetFunction.Column(Target))="Hello"
End If
End Sub

I have similar bits of code in the same worksheet_change sub that work fine when I use Target.Offset(1,0) but since my possible target range is in more than 1 Row, I don’t know how to make it so that it is always row 16 and the same column as the target….

How to&Answers:

You need to deal with situations where Target is more than a single cell and disable event handling so when you change a value on the worksheet, the Worksheet_Change doesn’t try to run on top of itself.

This will put ‘hello’ into the cell immediately to the right of any cell within B:G that changes; essentially you would be adding ‘hello’ to columns C:H on the associated row of each cell in Target.

Private Sub Worksheet_Change(ByVal Target As Range)

    if not intersect(target, Range(Cells(12, "B"), Cells(14, "G"))) is nothing then
        on error goto safe_exit
        application.enableevents = false
        dim t as range 
        for each t in intersect(target, Range(Cells(12, "B"), Cells(14, "G")))
            t.Offset(1,0) = "hello"
        next t
    End If

safe_exit:
    application.enableevents = true
End Sub