代码之家  ›  专栏  ›  技术社区  ›  JJ from Oregon

访问条件格式-用户界面上的VBA选项更少?

  •  0
  • JJ from Oregon  · 技术社区  · 8 年前

    问题是,虽然前端允许4个或更多条件,但当我尝试使用VBA设置条件时,在设置第4个条件时遇到了错误。换句话说,如果我只尝试在代码中设置3个条件,那么代码运行良好。

    我使用的是MS Access 2010。我需要为连续表单上的两个文本框设置条件格式。我知道旧版本的MS Access只允许一个文本框有3个条件,但我知道我可以在Access 2010中获得更多条件。我当前的应用程序使用用户界面有4个条件。在我对这个问题的研究中,一个人说,MS Access的更高版本允许多达50种条件。即使在查看Access 2010规范页面时,我也无法确认这一点。但我知道我至少可以得到3个以上的条件。

    以下是适用于最多3条记录的测试代码:

    Function fApplyConditionFormatNow()
    
    Dim objFormatConds As FormatCondition
    Dim i As Integer 'index number for specific format conditions
    Dim stSQL As String 'query to get list of categories
    Dim rs As DAO.Recordset
    
    i = 0
    
    'clear out just in case FormatConditions accidentially got saved
    'with the form at some point.
    Me.ID.FormatConditions.Delete
    
    'get a recordset containing the formatting information
    '(ie, get RGB values for each category type)
    stSQL = "SELECT * FROM tblTestConditionalFormatting;"
    fRunSQL stSQL, rs 'fRunSQL is custom code that gets runs stSQL and returns the recordset
    
    'loop through recordset to get conditional formatting values
    Do Until rs.EOF
        'create a condition on textbox named "ID".  The condition will be for
        'the Category/Type (TypeNm) that's up now in the recordset.
        Set objFormatConds = Me.ID.FormatConditions.Add(acExpression, , "[TypeNm] = '" & rs!TypeNm & "'")
        'add formatting for the condition just created.
        With Me.ID.FormatConditions(i)
            .BackColor = RGB(rs!RGB1, rs!RGB2, rs!RGB3)
        End With
        i = i + 1
        rs.MoveNext
    Loop
    
    rs.Close
    Set rs = Nothing
    
    End Function
    

    当类别表中包含4条记录时:即tblTestConditionalFormatting,我得到以下错误: “运行时错误7966:指定的格式条件大于格式条件数。”

    因此,前端可以处理3个以上的条件,而VBA对象只能处理3个条件,这似乎是一个错误?也许我做错了什么。还有其他人遇到过这个吗?你有解决问题的办法吗?

    非常感谢。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Andre    8 年前

    而不是 With Me.ID.FormatConditions(i) ,使用 FormatCondition 您刚刚创建的对象:

    Set objFormatConds = Me.ID.FormatConditions.Add(acExpression, , "[TypeNm] = '" & rs!TypeNm & "'")
    'add formatting for the condition just created.
    With objFormatConds 
        .BackColor = RGB(rs!RGB1, rs!RGB2, rs!RGB3)
    End With
    

    你不需要 i 不再

    我有类似的代码(简化)如下:

    For i = 1 To 6
        lColor = DLookup("Color", "someTable", "p_Color_ID = " & i)
        Set objFrc = txtFld.FormatConditions.Add(acExpression, , "[ColorGroup] = '" & i & "'")
        objFrc.BackColor = lColor
    Next i
    

    编辑

    显然,您可以编辑FormatConditions>=3如果不触摸0..2:
    https://access-programmers.co.uk/forums/showthread.php?t=271679

    也许我有这样的东西…:/