【问题标题】:Setting Access Colour Codes in VBA在 VBA 中设置访问颜色代码
【发布时间】:2017-03-28 01:46:45
【问题描述】:

我在我的 Access 数据库中设置文本框的背景颜色时遇到问题。我想在满足某些条件时将颜色更改为红色。

在设计视图中,我将文本框的背景颜色属性设置为红色,并显示为“#ED1C24”。当我在表单视图中查看表单时,控件以我选择的红色正确显示。

但是,当我将此值放入我的 VBA 代码 (Text1.Backcolor = "#ED1C24") 时,我收到类型不匹配错误。

我尝试将其更改为十六进制数字 (Text1.Backcolor = &HED1C24),但随后控件变为蓝色。

任何帮助将不胜感激。谢谢。

【问题讨论】:

标签: ms-access


【解决方案1】:

不久前我写了一篇关于这个问题的博客,应该可以回答你的问题。

http://www.jht.co.uk/access-colour-color-codes/

代码如下:

Public Function HTMLColour(HTMLCode As String, Optional Red As Variant, _
Optional Green As Variant, Optional Blue As Variant) As Long
On Error GoTo HTMLColour_Error

'Converts an HTML colour code number to a long interger
'Also returns the constituent R,G & B components through supplied parameters

Dim intR As Integer, intG As Integer, intB As Integer
Dim strHTML As String

'Strip # prefix if supplied
If Len(HTMLCode) < 6 Then Exit Function
strHTML = Right(HTMLCode, 6)

'Extract R, G, B values
intR = CInt("&H" & Mid(strHTML, 1, 2))
intG = CInt("&H" & Mid(strHTML, 3, 2))
intB = CInt("&H" & Mid(strHTML, 5, 2))

'Return optional parameters
If Not IsMissing(Red) Then Red = intR
If Not IsMissing(Green) Then Green = intG
If Not IsMissing(Blue) Then Blue = intB

'Convert RGB to Long integer
HTMLColour = RGB(intR, intG, intB)

HTMLColour_Exit:
Exit Function

HTMLColour_Error:
MsgBox Err.Description, vbExclamation, "Function HTMLColour"
Resume HTMLColour_Exit
End Function

希望这会有所帮助。

【讨论】:

  • 始终欢迎提供指向潜在解决方案的链接,但请add context around the link,以便您的其他用户知道它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。考虑到仅仅是指向外部站点的链接Why and how are some answers deleted? 的一个可能原因。
【解决方案2】:

VBA 中的颜色代码格式是 RGB 或 Long,而不是 HEX

在您的情况下,最简单的方法是调用将从 HEX 转换为 Long 的函数:

Public Function Color_Hex_To_Long(strColor As String) As Long
    Dim iRed As Integer
    Dim iGreen As Integer
    Dim iBlue As Integer

    strColor = Replace(strColor, "#", "")
    strColor = Right("000000" & strColor, 6)
    iBlue = Val("&H" & Mid(strColor, 1, 2))
    iGreen = Val("&H" & Mid(strColor, 3, 2))
    iRed = Val("&H" & Mid(strColor, 5, 2))

    Color_Hex_To_Long = RGB(iRed, iGreen, iBlue)
End Function

像这样使用它:

Text1.BackColor = Color_Hex_To_Long("#ED1C24")

【讨论】:

  • 这对我没有工作(Access 365) - 从 Access 表单属性中显示的十六进制值计算的整数与我通过读取颜色得到的不同手动设置后按代码编号=>结果颜色错误。下面 jhTuppeny 的解决方案完成了这项工作。
【解决方案3】:

只需使用 OnCurrent 属性来设置您的字体属性或其他属性。 无需输入十六进制颜色代码,而是更容易使用完全以数字表示的 MS Access 专有代码。做简单的方法。干杯!米奇

【讨论】:

    【解决方案4】:

    对于 MS_ACCESS 2016,long 值似乎只是 .backcolor 值,使用上述函数转换 HEX 不起作用。

    我只需创建一个文本框和一个标签,在设计视图中为标签着色,然后在 VBA 中将文本框值设置为 txtBlue = lblBlue.backcolour。

    我不确定在其他版本的 excel 中是否是这种情况,但在 Office 2016 中似乎是这种情况。

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2020-02-26
      相关资源
      最近更新 更多