简体   繁体   中英

A continuous macro to clear adjacent cells Excel VBA

I'm trying to create a continuous macro that would check for an error in a column, and if there is, would clear the contents in an adjacent cell. The Column with the error has a formula that would fill in data depending on what value is in the adjacent cell. So I want program to clear away the value of the adjacent cell if an invalid value was inputted. This is what I have so far, but I am unsure how to specify an adjacent cell to the associated error. I put in the X to indicate a varied row value.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Set ws = Worksheet(1)
        If Target.Column = 2 Then
            If IsError(Target.Value) Then
               *- Range("AX").ClearContents -*
            End If
        End If
End Sub

The problem with the code you have is that you are using the Worksheet_Change event and identifying the formula cell as the target. This will never work as changes in formula results do not get triggered by the Worksheet_Change event. (You can process these with the Worksheet_Calculate event though - but that is not what you need here). The cell actually be changed needs to be evaluated.

What would probably serve you better is Data Validation set up on the input cells to ensure the correct input is provided. In this way, no VBA is necessary. However, if that doesn't work, the code below will work.

Private Sub Worksheet_Change(ByVal Target As Range)
'worksheet_change will always work on the current worksheet, only identify _
another worksheet if you want to act on a range in a different sheet

'-> 3 assumes the input column is C (based on your description)
If Target.Column = 3 And IsError(Target.Offset(,-1)) And Target.Rows.Count = 1 and Target.Columns = 1 Then 

    Application.EnableEvents = False
    Target.Offset(,-1).ClearContents
    'Msgbox "Enter a valid value." ' possible warning message
    Application.EnableEvents = True

End If

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