对象单元格/区域不支持 。VBA 中的字体属性



我正在尝试对单元格进行颜色编码,以便在运行计算之前向用户发出有关哪个单元格的数据不正确的警告。目前正在抛出:

运行时错误 438 对象不支持属性

尝试运行所有数据时。

基本上创建一个工作表以允许用户在组合上输入一些数据,然后基于一些后端数据/限制,吐出他们可以/不能做什么的答案。当用户输入数据时,我已经在初始代码中进行了一定程度的错误检查(基本上是为了尝试并鼓励他们在尝试运行计算之前确保他们输入的数据有效),这使用Worksheet_Change子例程工作正常,它可以一次循环一个单元格(在目标范围内)不用担心。

如果我尝试复制它(使用命名范围而不是 change 函数中的目标单元格),它似乎会做两件事之一:它将尝试通过一系列单元格而不是单个单元格发送,并在尝试匹配来自"单元格"而不是它应该尝试匹配的单个单元格的数据时失败, 或者,当它尝试为其着色时,它将抛出 438 错误。

Private Sub CommandButton1_Click()
Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range
ErrorWagonPack = False
ErrorCellsNotEmpty = False
Set Target = Application.Range("ConsistInput")
For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
Application.EnableEvents = False
WagonPack = 0
If Len(cel.Value) > 0 Then
WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
ErrorWagonPack = True
cel.Font.ColourIndex = RGB(156, 0, 6) '438 error here
cel.Interior.ColourIndex = RGB(255, 199, 206) '438 error here too
End If
End If
Next cel
If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
Exit Sub
End If
'calculate stuff
Application.EnableEvents = True
End Sub

理想情况下,我想达到运行代码的地步,为导致问题/数据不正确的单元格着色,然后如果没有抛出任何错误变量,则运行计算,但 438 错误似乎是症结所在。我几乎愿意打赌这是我错过但无法弄清楚的简单东西。可能无济于事,我对 VBA 仍然很环保。

.ColorIndex不正确。使用.Color

Private Sub CommandButton1_Click()
Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range
ErrorWagonPack = False
ErrorCellsNotEmpty = False
Set Target = Application.Range("ConsistInput")
For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
Application.EnableEvents = False
WagonPack = 0
If Len(cel.Value) > 0 Then
WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
ErrorWagonPack = True
cel.Font.Color = RGB(156, 0, 6) '438 error here
cel.Interior.Color = RGB(255, 199, 206) '438 error here too
End If
End If
Next cel
If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
Exit Sub
End If
'calculate stuff
Application.EnableEvents = True
End Sub

.ColorIndex属性介于 1 和 56 之间:

Sub TestMe()
Dim cel As Range
Set cel = Worksheets(1).Range("A1")
cel.Interior.ColorIndex = 1
cel.Font.ColorIndex = 20
End Sub

2 个 RGB 值比 56 更远:

Sub TestMe()
Debug.Print RGB(156, 0, 6)          '393372
Debug.Print RGB(255, 199, 206)      '13551615
End Sub

因此,唯一要安全使用的值是 56 个红色值,介于以下两者之间:

cel.Font.ColorIndex = RGB(56, 0, 0)

cel.Font.ColorIndex = RGB(1, 0, 0)

作为替代方案,不使用ColorIndexRange().Font.Color支持完整的 RGB 值:

Range("A1").Font.Color = RGB(100, 20, 255)

最新更新