首页 > 解决方案 > 如何在特定列中始终将单元格格式设置为负数?

问题描述

在此处输入图像描述

我想为现有库存数量制作一个简单的跟踪表。F 列是实际库存数量,将汇总所有行单元格的值。列包括。“出口”(例如 H 和 J 列)应为负值。

我已经尝试了以下代码。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim isect As Range
Set isect = Application.Intersect(Target, Range("I:I"))
If Not (isect Is Nothing) Then
    If Target.Value > 0 Then Target.Value = 0 - Target.Value
End If

End Sub

它会自动将“I”列变为负数。但是,我将来会添加更多批次。如果列包含“导出”,是否有任何方式自动变为负数?

标签: excelvba

解决方案


我建议如下:

如果您没有其他方法可以确保“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但由于我不记得我停止这样做并使用公共布尔值的原因。


推荐阅读