2016-09-28 59 views
0

我的工作表現在有以下代碼。當我在列E中輸入數據時,評論「新」的返回值(例如日期)在列B,D和F中分別可以正常工作。如果刪除其他單元所依賴的主數據,如何清除其他單元的內容?

然而,當我刪除列E中的數據,在列B返回值,d和F保持在那裏。

如何刪除我在列E中輸入的數據,如何清除它們?

非常感謝!

私人小組Worksheet_Change(BYVAL目標作爲範圍)

Dim i As Integer 
For i = 2 To 10000 
    If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then 
     Cells(i, "B").Value = Date 
     Cells(i, "B").NumberFormat = "dd.mm.yyyy" 
     Cells(i, "D").Value = "NEW" 
     Cells(i, "F").Value = "NEW" 
    End If 

回答

1

如果你的意思是,如果你明確的E列的內容,然後在列B,d和F清除的內容,然後用下面

代碼

(可是,爲什麼你需要掃描整個行,對每一個細胞的變化?)

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim i    As Integer 

For i = 2 To 10000 
    If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then 
     Cells(i, "B").Value = Date 
     Cells(i, "B").NumberFormat = "dd.mm.yyyy" 
     Cells(i, "D").Value = "NEW" 
     Cells(i, "F").Value = "NEW" 
    Else 
     If Cells(i, "E").Value = "" Then 
      Cells(i, "B").ClearContents 
      Cells(i, "D").ClearContents 
      Cells(i, "F").ClearContents 
     End If 
    End If 

Next i 

End Sub 

改進代碼:只運行如果列E中的單元格發生更改,則該代碼僅修改該行的列B,D和F中的單元格的值。

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim WatchRange     As Range 
Dim IntersectRange    As Range 

' can modify it to your need, also using dynamic last row with data 
Set WatchRange = Range("E2:E10000") 
Set IntersectRange = Intersect(Target, WatchRange) 

' check values in Column E, only if cells in Column E are modified 
If Not IntersectRange Is Nothing Then 
    Dim i    As Integer 

    ' change value only for relevant row change 
    i = Target.Row 

    If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then 
     Cells(i, "B").Value = Date 
     Cells(i, "B").NumberFormat = "dd.mm.yyyy" 
     Cells(i, "D").Value = "NEW" 
     Cells(i, "F").Value = "NEW" 
    Else 
     If Cells(i, "E").Value = "" Then 
      Cells(i, "B").ClearContents 
      Cells(i, "D").ClearContents 
      Cells(i, "F").ClearContents 
     End If 
    End If 

End If 

End Sub 
+0

我試過上面提到的方法,但是,它每次嘗試輸入新數據時都會掛起我的程序。謝謝。 (: – Vivien

+0

您是否嘗試過我的「改進」部分中的代碼? –

+0

作品很有魅力!謝謝! – Vivien

相關問題