我目前有这段运行的代码,它对M列中具有特定值的单元格左侧和右侧的行执行计算。我在单元格列上使用数据验证以确保选择正确的条目。问题是,现在代码运行时间太长,因为每次更改单元格时,它都会重新计算指定范围内的所有单元格。我希望它只能在已更改的行上运行,而不是在任何其他单元格上运行。任何建议都会很棒:)
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim KeyCells As Range
Set KeyCells = Range("$J$4", "$M$2000")
If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
Dim x As Range
Range("D2").Value = Environ("username")
Range("B2") = Date
For Each x In Range("$M$4", "$M$2000")
Select Case x.Value
Case "6 Realization":
x.Offset(0, 1).Value = 1
If x.Offset(0, -2) = "" Then
x.Offset(0, -1).Value = x.Offset(0, -3) - x.Offset(0, -2).Value '
Else
x.Offset(0, -1).Value = x.Offset(0, -2) - x.Offset(0, -3).Value
End If
Case "7 Complete":
x.Offset(0, 1).Value = 1
If x.Offset(0, -2) = "" Then
x.Offset(0, -1).Value = x.Offset(0, -3) - x.Offset(0, -2).Value
Else
x.Offset(0, -1).Value = x.Offset(0, -2) - x.Offset(0, -3).Value
End If
Case "5 In Progress":
If x.Offset(0, -3).Value = "" Then
x.Offset(0, 1).Value = ""
Else
x.Offset(0, 1).Value = (Date - (x.Offset(0, -3).Value)) / ((x.Offset(0, -2).Value) - (x.Offset(0, -3).Value))
End If
x.Offset(0, -1).Value = Date - x.Offset(0, -3).Value
If x.Offset(0, -2).Value = "" Then
x.Offset(0, 1).Value = ""
End If
Case "4 Chartered":
x.Offset(0, 1).Value = ""
x.Offset(0, -1).Value = Date - x.Offset(0, -3).Value
Case "1 Ideas":
x.Offset(0, 1).Value = ""
x.Offset(0, -1).Value = Date - x.Offset(0, -3).Value
Case "8 On Hold":
x.Offset(0, 1).Value = ""
x.Offset(0, -1).Value = Date - x.Offset(0, -3).Value
Case "9 Terminated":
x.Offset(0, 1).Value = ""
If x.Offset(0, -2).Value = "" Then
x.Offset(0, -1).Value = x.Offset(0, -3) - x.Offset(0, -2).Value
Else
x.Offset(0, -1).Value = x.Offset(0, -2) - x.Offset(0, -3).Value
End If
Case "2 OpID":
x.Offset(0, 1).Value = ""
x.Offset(0, -1).Value = Date - x.Offset(0, -3).Value
End Select
If x.Offset(0, -1).Value > 40000 Or x.Offset(0, -1).Value = 0 Then
x.Offset(0, -1).Value = ""
End If
If x.Offset(0, 1).Value >= 1 Then
x.Offset(0, 1).Value = 1
End If
If x.Offset(0, 1).Value < 0 Then
x.Offset(0, 1).Value = 0
End If
Next
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
离开Application.Calculation = xlCalculationManual
,然后使用Range("Your range to recalculate").Calculate
来完成该部分。如果您将第一部分更改回xlCalculationAutomatic
,那么它将再次完成您的整个工作表,因此请将其保留为手册。