事件触发 VBA 宏运行,但不执行

Event triggered VBA Macro runs, but doesn't execute

我有一个带计算项的枢轴 table。每次,当我更改数据透视主过滤器中的参数时,文本格式都会返回默认值。

为了不每次都格式化 table,我创建了一个宏,每当我在单元格 D1 中放置一个值时,它应该格式化主元 table。 C2 是格式示例单元格。似乎宏运行了,但没有执行。

你能帮忙吗?

代码:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$d" Then

Application.EnableEvents = False

    Range("C2").Activate
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ORAZ(JEŻELI($B2=" 'OFERTA/TOTAL RYNEK'";1;0);JEŻELI(C2>1;1;0))"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399945066682943
    End With

    Selection.FormatConditions(1).StopIfTrue = False
    Range("C2").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ORAZ(JEŻELI($B1=""OFERTA/TOTAL RYNEK"";1;0);JEŻELI(C1>1;1;0))"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

    With Selection.FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399945066682943
    End With

    Selection.FormatConditions(1).StopIfTrue = False
    Selection.Copy
    Columns("C:N").Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False

Application.EnableEvents = True

End If

End Sub

比较两个字符串,例如 Target.Address"$d" 使用以下内容:

If Target.Address = "$d" Then

.. 永远不能等同于 TRUE,就好像 Target.Address 确实引用了第 4 列第 1 行,它将包含字符串 "$D"。使用=进行比较本质上是使用二进制比较.

您需要将其更正为 "$D",或者使用带有 StrComp 函数的 Text Compare 方法。

逐步浏览事件,并将鼠标悬停在 Target.Address 上会突出显示这一点。

正如另一位发帖人所提到的 - 二进制比较永远不会评估你对 True 的论证你可以将地址保存为字符串并将参数更改为 If Target.Address = [Assigned String Name] Then 但它更好只需将参数更改为以下内容:

If Not Intersect(Target, Range("$D")) Is Nothing And Target.Cells.Count = 1 Then

    'code here

End If

这降低了代码行为不符合您预期的风险,并且因为它仅在 D1 更改时才传递参数,并且正如下面的评论所述,这是更合适的代码。