简体   繁体   English

一个连续的宏以清除相邻的单元格Excel VBA

[英]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. 我输入X以指示变化的行值。

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. 您的代码存在的问题是您正在使用Worksheet_Change事件并将公式单元格标识为目标。 This will never work as changes in formula results do not get triggered by the Worksheet_Change event. 由于公式结果的更改不会被Worksheet_Change事件触发,因此它将永远不会起作用。 (You can process these with the Worksheet_Calculate event though - but that is not what you need here). (尽管您可以使用Worksheet_Calculate事件处理这些事件-但这不是您所需要的)。 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. 这样,就不需要VBA。 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

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

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