添加条件格式

问题描述 投票:0回答:1

导致“运行时错误'-2147417848'(80010108)'”

我有一些代码创建一个新的工作簿,导入一些数据,然后添加条件格式。

问题:它不起作用,引用主题行中的错误。问题不在于错误引用的方法,问题是代码实际上没有添加FormatCondition - 这在之后的CF窗口中是可见的 - 因此我尝试调用的所有方法都会失败并出现相同的错误。

...除非我从头开始执行代码;在这种情况下,它按预期工作 - FormatCondition正常添加,看不到错误,并且CF在工作表上可见,正是我想要它做的事情。

截图: enter image description here

相关代码:

Public wb As Workbook, ws As Worksheet

Sub Main()
    Set wb = Workbooks.Add
    Set ws = wb.Worksheets(1)
    ' Populate ws with some data
    Call FixCF(ws)
End Sub

Sub FixCF(ByRef cfWs As Worksheet)
    cfWs.Cells.FormatConditions.Delete

    Debug.Print "Start CF"
    With cfWs.Range("G:G").FormatConditions
        .Add Type:=xlExpression, Formula1:="=(INDIREKTE(ADRESSE(RAD(); 12))=""G"")"
        .Item(1).SetFirstPriority
        .Item(1).Interior.PatternColorIndex = xlAutomatic
        .Item(1).Interior.Color = 14277081
        .Item(1).StopIfTrue = False
    End With
End Sub

我也试过这个变种:

cfWs.Range("G:G").FormatConditions.Add Type:=xlExpression, Formula1:="=(INDIREKTE(ADRESSE(RAD(); 12))=""G"")"
With cfWs.Range("G:G").FormatConditions(1)
    .SetFirstPriority
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.Color = 14277081
    .StopIfTrue = False
End With

这是宏录制器吐出的代码:

Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=(INDIREKTE(ADRESSE(RAD(); 12))=""G"")"

Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 5296274
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False

我没有使用我通过谷歌推测的那些通常的罪魁祸首 - ActiveSheetSelection - 而且我已经尝试了Application.WaitDoEvents,行为没有变化。我假设它不是腐败工作簿的问题,因为我在宏的每次运行中创建一个新的 - 但我尝试使用相同的代码制作一个全新的工作簿,以确保,我得到同样的错误。我已多次关闭并重新打开“主机表”(包括整个Excel应用程序) - 仍然没有。

所以我的问题仍然存在:为什么代码只在我单步执行时才有效?

excel vba excel-vba conditional-formatting
1个回答
0
投票

当我单步执行代码时它起作用的原因是因为我在查看表时正在查看表单。在perpetrating子的顶部添加一个简单的cfWs.Activate修复了一切。

@Zac提到如果您使用工作表的名称而不是其索引,它会起作用。我还没有尝试过,但是我会把它包含在这里给任何发现这个帖子同样问题的人。

因此,看起来教训是你不能总是将条件格式添加到工作表中,除非它也是活动工作表 - 据我所知,doesn't appear on MSDN有点消息。

© www.soinside.com 2019 - 2024. All rights reserved.