[英]Delete entire based on another cell value
我需要 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
但它显示一个错误。
请尝试下一个改编的代码:
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
值是一个数字,而不是一个看起来像数字的字符串。 如果是字符串,您可以将它们放在双引号之间,就像在您的初始代码中一样。
当然,一个名为“周计划”的工作表必须存在于活动工作簿中,并且不得受到保护。
了解您遇到的错误会有所帮助。 假设错误是由于“ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.