简体   繁体   中英

Change cell if other cell contains text vba

I used to have the following code and it used to work but for some reason it no longer works.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim test As Range
Dim KeyCells As Range
Dim i As String


    Set KeyCells = Range("AF3:AF5000")
    test = Target.Rows.Count


    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        For i = Target.Row To (Target.Row + (Target.Rows.Count - 1))
            If Not ActiveSheet.Cells(i, 32) = "" Then
                ActiveSheet.Cells(i, 20).Value = "Closed"
            End If
        Next

    End If
End sub

Basically if there is data in any cells of column AF then the cell align with the information in column T would mark Closed. For example if AF65 <>"" then T65.value ="Closed"

Any idea why it no longer works or if there is another possibility for a macro?

Get rid of the redundant code and non-specific worksheet references. For example, a Worksheet_Change can be triggered when that worksheet is not the Activesheet; putting in Activesheet when it is not required only confuses the issue.

You also are not disabling events so your sub is going to try to run on top of itself.

This should be closer to what you are attempting to perform.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim trgt As Range
        For Each trgt In Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange)
            If CBool(Len(trgt.Value2)) Then
                trgt.Offset(0, -12) = "Closed"
            Else
                trgt.Offset(0, -12) = vbNullString
            End If
        Next trgt
    End If

safe_exit:
    Application.EnableEvents = True
End Sub

If your original sub just 'stopped working' then put Application.EnableEvents = True into the VBE's Immediate window and tap [enter]. It is possible that your earlier code crashed with event handling disabled.

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