2017-03-08 237 views
2

我有一個Excel工作表與一些VBA代碼,當我改變一個特定的單元格時,它會自動將今天的日期設置到它旁邊的單元格中。Excel Worksheet_Change事件觸發時刪除行

這一切都很好,但是當我刪除特定單元格上方的整行時,它會自動將日期更改爲今天的日期。

這是我使用的代碼會自動更改單元格:

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim WorkRng As Range 
Dim Rng As Range 
Dim xOffsetColumn As Integer 
Set WorkRng = Intersect(Application.Sheets("Example").Range("H10: H306, M10: M306, R10: R306, W10: W306, AB10: AB306, AG10: AG306"), Target) 
xOffsetColumn = 1 
If Not WorkRng Is Nothing Then 
    Application.EnableEvents = False 
    For Each Rng In WorkRng 
     If Not VBA.IsEmpty(Rng.Value) Then 
     Sheets("Example").Unprotect 
      Rng.Offset(0, xOffsetColumn).Value = Now 
      Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy" 
     Sheets("Example").Protect 
     Else 
      Rng.Offset(0, xOffsetColumn).ClearContents 
     End If 
    Next 
    Application.EnableEvents = True 
End If 
End Sub 

是有人熟悉這個問題?

回答

0

你可以做一些測試的範圍Target,避免執行代碼
(與Goto或者說Exit Sub):

  • Target.Cells.Count > 1
  • Target.Rows.Count > 1
  • Target.Columns.Count > 1

你可以使用這些t在小組的開始或If Not WorkRng Is Nothing Then

的EST所以,你的代碼可能是:

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim WorkRng As Range 
Dim Rng As Range 
Dim xOffsetColumn As Integer 

If Target.Columns.Count > 1 Then Exit Sub 

Set WorkRng = Intersect(Application.Sheets("Example").Range("H10: H306, M10: M306, R10: R306, W10: W306, AB10: AB306, AG10: AG306"), Target) 
xOffsetColumn = 1 
If Not WorkRng Is Nothing Then 
    Application.EnableEvents = False 
    For Each Rng In WorkRng 
     If Not VBA.IsEmpty(Rng.Value) Then 
     Sheets("Example").Unprotect 
      Rng.Offset(0, xOffsetColumn).Value = Now 
      Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy" 
     Sheets("Example").Protect 
     Else 
      Rng.Offset(0, xOffsetColumn).ClearContents 
     End If 
    Next 
    Application.EnableEvents = True 
End If 
End Sub 
+0

非常感謝您!這解決了我的問題。 – Graaf

+0

很高興能幫到你! ;)@Graaf – R3uK