【发布时间】: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 下出错。