【问题标题】:Application or object defined error when trying to change background and font colors尝试更改背景和字体颜色时出现应用程序或对象定义错误
【发布时间】:2015-01-22 23:36:58
【问题描述】:

我正在尝试替换电子表格的所有条件格式(超过 30 条格式规则)。我创建了一个类模块(称为 ConditionalFormatting),其中包含所有格式规则的一系列子项,每个需要条件格式的范围都有一个子项。 我想到的唯一方法(接受建议)是让 worksheet_change 事件调用 ConditionalFormatting 类中名为 FormattingSubs 的子程序,它将调用正确的子程序来执行格式化。

这是 FormattingSubs 的代码:

Public Sub FormattingSubs(target As Range)
    'have logic here to call the right sub based on what target.address
    'is from the worksheet.change event

    Select Case target.Name.Name
        Case "head_pouch_lot_number"
            Call HeadPouchLotNumber(target)
        Case "head_consumed_pouch_lot"
            Call HeadConsumedPouchLot(target)
        Case "section_one_heading"
            Call SectionOneHeading
    End Select

End Sub

这是其中一个格式化子程序 HeadConsumedPouchLot 的代码:(请注意,颜色变量是在单独的模块中定义的公共常量)

Public Sub HeadConsumedPouchLot(target As Range)
    Dim head_consumed_pouch_lot As Range
    Dim ws As Worksheet
    Set head_consumed_pouch_lot = ActiveSheet.Range("head_consumed_pouch_lot")
    Set ws = target.Worksheet

    If target.address <> head_consumed_pouch_lot.address Then
        Set target = head_consumed_pouch_lot
    End If

    With ws.Range(target.address)
        If Range("section_one_heading").Value <> "" Then
            .Interior.ColorIndex = red
            .Font.ColorIndex = yellow
        Else
            .Interior.ColorIndex = lightgreen
            .Font.ColorIndex = black
        End If
    End With

问题是当它去实际设置颜色时,它给了我 1004 错误:“应用程序定义或对象定义的错误。”

我的代码有什么问题?

【问题讨论】:

  • target 在哪个工作表上?
  • 错误实际出现在哪一行?
  • 如果 "head_consumed_pouch_lot" 是工作簿中的命名范围,则可以使用 ThisWorkbook.Names("head_consumed_pouch_lot").RefersToRange 代替 ActiveSheet
  • @RusanKax 当我从工作表更改事件中调用 FormattingSubs 例程时,目标位于已更改单元格所在的工作表上。在这种情况下,“head_consumed_pouch_lot”在表 1 上,名为“FA-201C”。
  • @PatricK .Interior.ColorIndex = 上的代码错误。它会在 If 或 Else 下出错。

标签: vba excel


【解决方案1】:

我发现的问题是我需要先取消保护我的工作表,然后才能对其进行任何更改!谢谢大家帮我寻找答案。

【讨论】:

  • 这很有帮助 - Excel 在此处的行为不一致,因为允许 VBA 对评论的格式进行其他更改,但不能对字体颜色进行更改。我怀疑这不是设计使然,而且需要不受保护的工作表绝对不是显而易见的或直观的。取消保护工作表确实为我解决了同样的问题。
猜你喜欢
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多