【问题标题】:Delete entire based on another cell value根据另一个单元格值删除整个
【发布时间】:2022-01-02 11:48:07
【问题描述】:

我需要有关 Excel VBA 代码的帮助。

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 3 And Target.Cells.Count = 1 Then
    If LCase(Target.Value) = "-1" Then
        With Target.EntireRow.ClearContents
        End With
    End If
End If
If Target.Column = 3 And Target.Cells.Count = 1 Then
    If LCase(Target.Value) = "1000" Then
        With Target.EntireRow
            .Copy Sheets("Week Schedule").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            .Delete
        End With
    End If
End If
End Sub

如果我们在第三列输入-1,它将清除该行。如果我们输入 1000,它将被复制到另一个工作表并从当前工作表中删除。

上面的代码工作正常。我不想清除行数据,而是想删除该行。 所以加了

Line 4 With Target.EntireRow.ClearContents to With Target.EntireRow.Delete

但它显示一个错误。

【问题讨论】:

  • 请用= -1 替换= "-1"。否则,条件将查找字符串。然后,不需要两次迭代。你可以只用一个。并且您必须在删除范围之前将EnableEvents 设为False,这将再次触发Change 事件...
  • 我想您想要检查数字(-1 和 1000),而不是看起来像数字的字符串。这种理解正确吗?
  • 删除第 4 行的 WithEnd With

标签: excel vba excel-formula excel-2010


【解决方案1】:

了解您遇到的错误会有所帮助。假设错误是由于 Week Schedule 工作表不存在而引起的,您可以为此添加检查。之后,您的代码就可以正常工作了:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 3 And Target.Cells.Count = 1 Then
    If LCase(Target.Value) = "-1" Then
        With Target.EntireRow.ClearContents
        End With
    End If
End If
If Target.Column = 3 And Target.Cells.Count = 1 Then
    If LCase(Target.Value) = "1000" Then
        With Target.EntireRow
            SheetExistsOrCreate ("Week Schedule")
            .Copy Sheets("Week Schedule").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            .Delete
        End With
    End If
End If
End Sub

Function SheetExistsOrCreate(name As Variant)
For i = 1 To Worksheets.Count
    If Worksheets(i).name = "MySheet" Then
        exists = True
    End If
Next i

If Not exists Then
    Worksheets.Add.name = name
End If

End Function

【讨论】:

    【解决方案2】:

    请尝试下一个修改后的代码:

    Private Sub Worksheet_Change(ByVal Target As Range)
     If Target.Column = 3 And Target.Cells.Count = 1 Then
        Application.EnableEvents = False
         If LCase(Target.Value) = -1 Then        
            Target.EntireRow.Delete
         ElseIf Target.Value = 1000 Then
            With Target.EntireRow
                .Copy Sheets("Week Schedule").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
                .Delete
            End With
        End If
        Application.EnableEvents = True
     End If
    End Sub
    

    上面的代码假定Target 值表示一个数字,而不是一个看起来像数字的字符串。如果是字符串,您可以将它们放在双引号之间,就像在您的初始代码中一样。

    当然,一个名为“周计划”的工作表必须存在于活动工作簿中,并且不得受到保护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      相关资源
      最近更新 更多