简体   繁体   English

如果其他单元格包含文本vba,请更改单元格

[英]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. 基本上,如果在AF列的任何单元格中都有数据,则与T列中的信息对齐的单元格将标记为已关闭。 For example if AF65 <>"" then T65.value ="Closed" 例如,如果AF65 <>“”,则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; 例如,当该工作表不是Activesheet时,可以触发该工作表; putting in Activesheet when it is not required only confuses the issue. 在不需要时将其放入Activesheet只会使问题感到困惑。

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]. 如果您的原始子程序只是“停止工作”,则将Application.EnableEvents = True放入VBE的即时窗口中,然后点击[输入]。 It is possible that your earlier code crashed with event handling disabled. 您的早期代码可能会因禁用事件处理而崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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