我需要有關 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
但它顯示一個錯誤。
uj5u.com熱心網友回復:
了解您遇到什么錯誤會有所幫助。假設錯誤是由于作業 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
uj5u.com熱心網友回復:
請嘗試下一個改編的代碼:
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”的作業表,并且不得受到保護。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401370.html
標籤:擅长 vba excel-公式 excel-2010