2016-11-13 49 views
0

我有一個代碼,如果在同一行的單元格中進行任何更改在列F:Excel VBA更新單元格中的日期如果在同一行中的單元格範圍內有任何更改

Private Sub Worksheet_Change(ByVal Target As Range) 
' Code to put the date of the latest update following a change in the corresponding cell in column F 
Dim WorkRng As Range 
Dim rng As Range 
Dim xOffsetColumn As Integer 
Set WorkRng = Intersect(Application.ActiveSheet.Range("F:F"), Target) 
xOffsetColumn = -2 'The date is put 2 columns to the left of column F 
If Not WorkRng Is Nothing Then 
    Application.EnableEvents = False 
    For Each rng In WorkRng 
     If Not VBA.IsEmpty(rng.Value) Then 
      rng.Offset(0, xOffsetColumn).Value = Now 
      rng.Offset(0, xOffsetColumn).NumberFormat = "dd/mm/yyyy" 
     Else 
      rng.Offset(0, xOffsetColumn).ClearContents 
     End If 
    Next 
    Application.EnableEvents = True 
End If 
End Sub 

現在我需要去適應這個代碼,以便日期在列d的細胞更新,如果有變化的細胞由同一行中列F到K.

我有很少的VBA知識,並會感謝任何幫助適應代碼。

+1

'設置WorkRng =相交(Application.ActiveSheet.Range( 「F:K」),目標)' –

+0

那並不行不通:問題在於抵消:如果我在F列中更改了某些內容,那麼日期將放在D列(日期總是應該是的地方)。但是,如果我將列H中的內容更改爲K,則日期將放在左側的2列中。 – Antoon

+0

然後,您必須根據您的Target.Column在上面的代碼中更改'xOffsetColumn'。 – Ralph

回答

0

這似乎工作:

Private Sub Worksheet_Change(ByVal Target As Range) 
' Code to put the date of the latest update following a change in the corresponding cell in column F 
    Dim WorkRng As Range, roww As Long 
    Dim rng As Range 
    Set WorkRng = Intersect(Range("F:K"), Target) 
    If Not WorkRng Is Nothing Then 
     Application.EnableEvents = False 
      For Each rng In WorkRng 
       roww = rng.Row 
       If Not rng.Value = "" Then 
        Cells(roww, "D").Value = Now 
        Cells(roww, "D").NumberFormat = "dd/mm/yyyy" 
       Else 
        Cells(roww, "D").ClearContents 
       End If 
      Next 
     Application.EnableEvents = True 
    End If 
End Sub 

我們只是不使用OFFSET()

+0

非常感謝!這樣可行。 – Antoon

相關問題