Search code examples
excelfunctiontargetoffsetbyval

Change by Val, target as range not being recognized


Cells(R, DataCol).Resize(, ColumnCount).Copy
Cells(R, DataCol).Offset(RowOffset * (R - StartRow), ColOffset).PasteSpecial xlValues

Hey all, When I use the above code running from a module, it triggers a change by val written in the worksheet

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 15 Then
  Target.Offset(0, 1).Value = Now()
  End If
End Sub

Now the Cells part of the code is copying a block of four cells to column 12, reaching until column 15, but the change val isn't recognizing the 15th column as having a changed value. However when I change the target column to 11,

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 11 Then
   Target.Offset(0, 1).Value = Now()
   End If
End Sub  

the value is changed for the entire block of cells so four target changes are made.

Thanks.


Solution

  • How to process Target to account for >1 cell in the range:

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c as Range
    
    For each c in Target.cells
        If c.Column = 11 Then
           c.Offset(0, 1).Value = Now()
        End If
    Next c
    
    End Sub  
    

    or:

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng as Range
    
    Set rng = Application.Intersect(Target, Me.Columns(11))
    If not rng is nothing then
        rng.Offset(0, 1).Value = Now()
    End If
    
    End Sub 
    

    Also a good idea to disable events before you update the spreadsheet from your Change sub (otherwise you just re-trigger the event with your update). Use

     Application.EnableEvents=False 
    

    then set back to True when done (don't forget that part!)