Excel VBA:行中的范围更新时更改单元格中的日期;滞后码

nszi6y05  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(86)

我正在编写一个代码,当C列到R列中的任何单元格发生更改时,更改T列中的日期。
代码工作,但它使工作簿超级滞后和缓慢。有没有办法让这段代码更有效率?

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim WorkRng As Range, rrow As Long
    Dim Rng As Range
    Set WorkRng = Intersect(Range("B1:R300"), Target)
    If Not WorkRng Is Nothing Then
            For Each Rng In WorkRng
                rrow = Rng.Row
                If Not Rng.Value = "" Then
                    Cells(rrow, "T").Value = Now
                    Cells(rrow, "T").NumberFormat = "dd/mm/yyyy h:mm"
                Else
                    Cells(rrow, "T").ClearContents
                End If
            Next
    End If
End Sub
bxjv4tth

bxjv4tth1#

如果您想在B:R列中没有数据时清除时间戳,请尝试以下操作

Private Sub Worksheet_Change(ByVal Target As Range)
    Const FLAG_COL As String = "T"
    
    Dim WorkRng As Range, c As Range, rw As Range, cT As Range
    
    Set WorkRng = Intersect(Me.Range("B1:R300"), Target)
    If Not WorkRng Is Nothing Then
        For Each c In WorkRng.Cells
            Set rw = c.EntireRow
            Set cT = rw.Columns(FLAG_COL) 'timestamp cell
            'any data in B:R on this row?
            If Application.CountA(rw.Range("B1:R1")) > 0 Then
                cT.Value = Now
                cT.NumberFormat = "dd/mm/yyyy h:mm"
            Else
                cT.ClearContents
            End If
        Next
    End If
End Sub
p1tboqfb

p1tboqfb2#

时间戳在选定范围中的每一行更改时更新,如果行中的所有单元格都没有值,则删除时间戳。

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim checkRange As Range, changedRange As Range, wrkRow As Range, rrow As Long
   Dim Rng As Range
   
   Err.Clear
   On Error GoTo Lerr
   Application.EnableEvents = False
   Set checkRange = Range("B1:R300")
   Set changedRange = Intersect(checkRange, Target)
   If Not changedRange Is Nothing Then
      For Each Rng In changedRange
         rrow = Rng.row
         If Rng.value = vbNullString Then
            Set wrkRow = Intersect(Rng.EntireRow, checkRange)
            If WorksheetFunction.CountA(wrkRow) = 0 Then
               Cells(rrow, "T").ClearContents
            Else
               GoTo LsetTimeStamp
            End If
         Else
LsetTimeStamp:
            Cells(rrow, "T").value = Now()
            Cells(rrow, "T").NumberFormat = "dd/mm/yyyy h:mm:ss"
         End If
      Next
   End If
Lerr:
   Application.EnableEvents = True
   If Err.Number <> 0 Then
      MsgBox ("Error> " & Err.Number & vbCrLf & Err.Description)
   End If
   On Error GoTo 0
End Sub

相关问题