简体   繁体   中英

Can VBA code update a cell in a column of an Excel worksheet when a user enters data in a specific column range?

I have an Excel worksheet that is 12 columns wide and many rows deep. I'm trying to write a Worksheet_Change Sub that will cause the worksheet to automatically put in the current Date/Time, using the Now function, to Column L (or 12) in the same row that data was changed in a cell in columns AK or 1 through 11.

So far I have tried using the Offset function to accomplish this, but I can only find success in doing relative updates and not partially absolute updates. I tried using the Choose function in order to replace the offset function variable for column shift based on what cell the user is Targeting, but I can't get that to work either. Right now I'm attempting to use this, but to no avail:

Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range

Offst As Integer
End Type
Set WorkRng = Range("A:K")
If Not Application.Intersect(WorkRng, Range(Target.AddressLocal)) _
Is Nothing Then
If Target.Column = 1 Then Offst = 11
ElseIf Target.Column = 2 Then Offst = 10
ElseIf Target.Column = 3 Then Offst = 9
ElseIf Target.Column = 4 Then Offst = 8
ElseIf Target.Column = 5 Then Offst = 7
ElseIf Target.Column = 6 Then Offst = 6
ElseIf Target.Column = 7 Then Offst = 5
ElseIf Target.Column = 8 Then Offst = 4
ElseIf Target.Column = 9 Then Offst = 3
ElseIf Target.Column = 10 Then Offst = 2
ElseIf Target.Column = 11 Then Offst = 1
End If
    With Offst
            Target.Offset(0, Offst).Value = Now
            Target.Offset(0, Offst).NumberFormat = "dd-mmm-yyyy AM/PM"
    End With
End Sub

I'm very basic with VBA, and I don't have many hours behind it. I've searched the internet quite a bit, and I'd like to think I'm pretty good at exhausting search engines but I can't find something that directly relates to my situation. I can only find examples of people updating a single column of data, not a Range.

Any help is greatly appreciated! Thanks for taking the time!

No need for an offset. You can hard-code the L and use Intersect along with Target.EntireRow to update the corresponding rows in column L.

Simplified, the entire code could be:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Me.Range("A:K"), Target) Is Nothing Then Exit Sub

    Intersect(Me.Columns("L"), Target.EntireRow).Value = Now
    Intersect(Me.Columns("L"), Target.EntireRow).NumberFormat = "dd-mmm-yyyy AM/PM"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM