-->

VBA To Change BackColor Of Rectangle - Access

2019-09-12 00:07发布

问题:

So I'm trying to change the backcolor of a rectangle within Access. I know you can easily do this Box1.BackColor = RGB(0, 0, 0), however I want to enter a value into a textbox and then display that color value as soon as you update the textbox.

I thought the following would work, but it doesn't.

Textbox1 = 0, 0, 0

Dim P1 as String
P1 = "RGB(" + Textbox1.text + ")"
Box1.Backcolor = P1

How can I go about changing the backcolor on the fly?

回答1:

You could split the text, run the entries though int and feed it to RGB:

Dim A As Variant
A = Split(Textbox1.text,",")
Box1.BackColor = RGB(Int(A(0)),Int(A(1)), Int(A(2)))


回答2:

Based on your code, Eval() should work for you. The function evaluates a string as if were code. Backcolor is a long, btw so I adjusted your code accordingly.

Dim P1 as Long
P1 = eval("RGB(" + Textbox1.text + ")")
Box1.Backcolor = P1

Or you can ditch P1 and do this:

Box1.Backcolor = eval("RGB(" + Textbox1.text + ")")

Depending on what you are doing, you might just want to use the built in color dialog instead of entering text in a textbox.

Here's the API declaration and re-usable function

Declare Sub wlib_AccColorDialog Lib "msaccess.exe" Alias "#53" (ByVal Hwnd As Long, lngRGB As Long)

Function ChooseColor(nDefColor As Variant) As Long
  Dim lngColor As Long
  wlib_AccColorDialog Screen.ActiveForm.Hwnd, nDefColor
  ChooseColor = nDefColor
End Function

And here would be your box call to these functions; it's passing the default color of the box so that will be chosen when the dialog is open.

Box1.BackColor = ChooseColor(Me.Box1.BackColor)