vba选择目标后选择偏移单元格?不工作?

时间:2017-01-25 12:06:43

标签: excel vba

我正在使用此代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = True
    On Error GoTo Errormask

    With Target
        If .Column = 30 And .Row > 16 And .Value = "Remove" Then
            .EntireRow.Delete
            Target.Offset(, 2).Select
        End If
    End With

Errormask:
   Application.DisplayAlerts = False
   Exit Sub

End Sub

如果用户点击第30列中包含"删除"的单元格,则应删除该行,然后选择单元格1。

这不起作用。请有人告诉我我哪里出错了吗?

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = True
    On Error GoTo Errormask '<-- don't see the need for this line

    With Target
        If .Column = 30 And .Row > 16 And .Value Like "Remove" Then
            .EntireRow.Delete
            .Offset(, 2).Select
        End If
    End With

Errormask: '<-- don't see the need for this line
   Application.DisplayAlerts = False
   Exit Sub '<-- don't see the need for this line, anyway at the end of the Sub

End Sub

答案 1 :(得分:0)

with中,在删除整行之前,请在下面的行上进行偏移。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Target
If Target.CurrentRegion.Count = 1 And Target.Cells.Count = 1 Then
    If .Column = 30 And .Row > 16 And .Value Like "Remove" Then
        .Offset(1, 2).Select
        .EntireRow.Delete
    End If
End If
End With
Application.DisplayAlerts = False
End Sub

您确定在工作表的代码中有这个而不是在模块中吗?

修改

我添加了一个新的If来检查选择的单元格是否首先合并,并且只选择了一个单元格。