首页 > 解决方案 > 类属性错误“需要对象”,但工作正常

问题描述

vba的奇怪问题。我正在尝试创建具有表装饰属性的模块。在表单中,用户选择表格标题背景的颜色。颜色已更改,但有错误。我怎样才能解决这个问题?想法?

装饰模块:

Private sHeaderTextBackground As Double
Public sHeaderRange As Range

Public Sub initVars()
    Set sHeaderRange = Range("A1:F1")
End Sub

Public Property Let HeaderTextBackground(ByVal color As Double)
    Let sHeaderTextBackground = color
End Property

Public Property Get HeaderTextBackground() As Double
    HeaderTextBackground = sHeaderTextBackground
End Property

代码形式:

Private Sub changeStyleApplyButton_Click()
    'Call DecorationModule.initVars

    If Application.Dialogs(xlDialogEditColor).Show(40) = True Then
        MsgBox (VarType(ThisWorkbook.Colors(40))) '<--- 5 = vbDouble
        DecorationModule.HeaderTextBackground = ThisWorkbook.Colors(40) <---Error here
        DecorationModule.sHeaderRange.Interior.color = DecorationModule.HeaderTextBackground
    End If

标签: excelvba

解决方案


对于以后遇到此错误的人:确保您已Module正确命名,并且没有任何拼写错误。这应该涵盖大部分错误。


问题是ClassModule使用 a 而不是 a Module。代码应粘贴到Module(使用正确的名称)中,然后代码才能工作。确保sHeaderRange在执行代码之前初始化。如果您想确保它仅在您可以将initVars()sub 更改为:

Public Sub initVars()
    If sHeaderRange Is Nothing Then
        Set sHeaderRange = Range("A1:F1")
    End If
End Sub

推荐阅读