我建议如下:
如果您没有其他方法可以确保“export”下方的值为负数(例如 excel-formulas),请使用您的修改后的代码。
Option Explicit
Public EventsEnabled As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If EventsEnabled Then
EventsEnabled = False
Dim isect As Range
Dim exportRange As Range
Set exportRange = GetExportRange()
Set isect = Application.Intersect(Target, exportRange)
If Not (isect Is Nothing) Then
If Target.Value > 0 Then Target.Value = 0 - Target.Value
End If
EventsEnabled = True
End If
End Sub
Function GetExportRange() As Range ' get all columns were the first 3 rows contain "export"
Dim srchrng As Range
Dim cell As Range
Dim exprng As Range
Dim cletter As String
Set srchrng = Range("J1:XFD3") ' modify here for other search range
Set exprng = Range("I:I")
For Each cell In srchrng
If cell.Value = "export" Then
cletter = Split(Cells(1, cell.Column).Address, "$")(1) ' get the letter from the address
Set exprng = Union(exprng, Range(cletter & ":" & cletter))
End If
Next cell
Set GetExportRange = exprng
End Function
这应该可以正常工作。出于性能原因,您应该考虑在事件之后禁用事件_Change并在完成时启用它。你看看这个_Change事件是否改变了什么,另一个_Change事件会被触发。所以你可以在改变事物的同时改变事物。因此我建议使用EnableEvents布尔值。我已经使用了,Application.EnableEvents但由于我不记得我停止这样做并使用公共布尔值的原因。