Setting Access Colour Codes in VBA - ms-access

I'm having trouble setting the back ground colour of a textbox in my Access database. I want to change the colour to red when certain conditions are met.
In design view I've set the textbox's back color property to red and it is shown as '#ED1C24'. When I view the form in Form view the control is correctly shown in the red colour I've chosen.
But when I put this value into my VBA code (Text1.Backcolor = "#ED1C24") I get a type mismatch error.
I've tried changing it to a Hex number (Text1.Backcolor = &HED1C24) but then the control turns blue.
Any help would be appreciated. Thanks.

I wrote a blog about this very problem a while ago which should answer your question.
http://www.jht.co.uk/access-colour-color-codes/
Here's the code:
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
Hope this helps.

The color code format in VBA is RGB or Long, and not HEX
In your case the easiest way is to call a function that will convert from HEX to 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
Use it like this :
Text1.BackColor = Color_Hex_To_Long("#ED1C24")

Simply use OnCurrent properties to set your font properties or other properties.
Instead of entering the Hex color codes, easier to use MS Access proprietary codes that are entirely in numbers. Do the easy way. Cheers! Mikey

For MS_ACCESS 2016 the long value seems to be just the .backcolor value, converting the HEX using the functions above won't work.
I'd just create a text box and a label, colour the label as you wish in design view and set the textbox value to txtBlue = lblBlue.backcolour in VBA.
I'm not sure if this is the case in other versions of excel but it seems to be the case in Office 2016.

Related

Move to next control at end of string

I have a form with a control that has a mask. The mask accepts 10 numbers, I have them formatted as short text. I will not be doing any calculation on them. They are just a string of numbers. I want the control to change focus to another control when I enter that last character. Example: I enter 1111-10-1234, when I type 4, I want the focus to change to the next control. I tried to use Len to change focus but it always shows the length as 12 since I have 12 place holders. Any other suggestions.
You might use the SelStart property:
If Me!YourTextBox.SelStart = 12 Then
' Cursor has moved past the last position.
Me!SomeOtherControl.SetFocus
End If
You can recheck the length of a string with numbers only. Use the regular expression functional to get rid of non-number signs in the string:
Public Function f_NumberExtractor(ByVal str As String) As string
Dim objRegEx As Object
if len(str) >1 then
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "\D"
objRegEx.Global = True
f_NumberExtractor= objRegEx.Replace(str, vbNullString)
else
f_NumberExtractor=vbnullstring
end if
End Function
so, now u can have
len(f_NumberExtractor(me.cmbName.value))>11
check in your code.

Convert Column To Field Order

I am importing an excel spreadsheet into access, and requesting the user to input wchich column holds a userid and phone. Now on the access form, they will be string values, like A & R
I am trying to then convert the alpha value to a number value, but when I use this syntax it is not giving appropriate results. Such as the below produces # when I would want it to produce 3 - what is the appropriate way in Access to convert Letters to Column Numbers
Sub Test()
Dim colletter As String
colletter = "C"
Debug.Print Chr(Val(colletter) + 64)
End Sub
You are really close. You are going to want to use the ASC() function which returns the ASCII value of a character. When you subtract 64, it will get you the correct column index.
Sub Test()
Dim colletter As String
colletter = "C"
Debug.Print Asc(colletter) - 64
End Sub
*EDIT: I've added some controls for multiple letters and to make sure that the letters are upper case. This does, however, limit it to only having two letters, meaning column "ZZ" is your last column, but hopefully your user doesn't have more than 702 columns. :)
Sub Test()
Dim colLetter As String
Dim colNumber As Integer
Dim multiplier As Integer
colLetter = "AB"
multiplier = 0
'If there is more than one letter, that means it's gone through the whole alphabet
If Len(colLetter) > 1 Then
multiplier = Asc(Left(UCase(colLetter), 1)) - 64
End If
colNumber = (multiplier * 26) + Asc(Right(UCase(colLetter), 1)) - 64
Debug.Print colNumber
End Sub
Here's another solution that allows any number of letters, such as "ZZZZ". As you can tell, it is quite similar to the post by #BobtimusPrime.
Public Function RowLetterToNumber(ByVal RowLetter As String) As Integer
If Len(RowLetter) > 1 Then
RowLetterToNumber = RowLetterToNumber(Mid(RowLetter, 2))
RowLetterToNumber = RowLetterToNumber + 26
Else
RowLetterToNumber = Asc(RowLetter) - 64
End If
End Function
Sorry, but can't you simply use: =COLUMN()

VBA To Change BackColor Of Rectangle - Access

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?
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)))
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)

How to compare the format of text between Excel and Access (like color, bold etc)

In fact, what I am doing now is to realize the synchronization of Excel and Sharepoint, which means that Excel can update with the updating of Sharepoint, and the same for the inverse case.
As known, MS 2003 has no problem with this, but MS 2010 can just realize the fonction from Sharepoint -> Excel, but not the inverse way.
So I am thinking to add Access because there exists Access <-> Sharepoint, and so if I can realize la fonction Excel -> Access, that will solve my problem.
I have finished some parts of macros for this, and now I have realized the fundamental fonction of synchronization. However, there are some difficulties in dealing with the format of text. In Sharepoint and Access, to express the color is like this
<div><font color = "#ff0000">TEXT</font></div>, however in excel I have no idea about the expression of the string.
So how to do it? All suggestions or answers will be appreciated.
This is a very broad question and covers alot of possibilities, and this isn't a complete answer, but for comparing HTML to VBA formatting, you would need to individually break down each formatting option and convert it from HTML to VBA and determine the properties applied to the text, just as you stated above. Then you would need individual VBA functions to specify what you want to compare from the text.
That being said, this is just an example of how this can be achieved for font color comparison.
Given:
'example html: <div><font color = "#ff0000">TEXT</font></div>
Dim HTML_text : HTML_text = "<div><font color = '#ff0000'>TEXT</font></div>"
Dim font_color : fontcolor = Mid(HTML_text, instr(HTML_text, "#"), 7)
Would return "#ff0000" as a variable font_color Then you would need the excel function to convert Hex(#FF0000) to RGB (taken from -> Here):
Public Function HEXCOL2RGB(ByVal HexColor As String) As String
Dim Red As String
Dim Green As String
Dim Blue As String
Color = Replace(HexColor, "#", "")
Red = Val("&H" & Mid(HexColor, 1, 2))
Green = Val("&H" & Mid(HexColor, 3, 2))
Blue = Val("&H" & Mid(HexColor, 5, 2))
HEXCOL2RGB = Red & "," & Green & "," & Blue
End Function
Then to extract the fonts RGB in Excel to the RGB you recieved from HTML you would need the following function(taken from -> Here):
Function FontColorRGB(Target As Range) As String
Dim N As Double
N = Target.Font.Color
FontColorRGB = Str(N Mod 256) & "," & Str(Int(N / 256) Mod 256) & "," & Str(Int(N / 256 / 256) Mod 256)
End Function
Then to finally pull it all together, you would utilize both functions:
Dim XLFontClr : XLFontClr = FontColorRGB("A1:A2")
Dim RGB_clr : RGB_clr = HEXCOL2RGB(font_color) 'Returns "Red,Green,Blue" in string form.
If XLFontClr = RGB_clr Then
msgbox "web formatting and excel formatting compared successfully"
End If

Is there a way to right-align a numeric column in a ListBox

We have a standard Access listbox with multiple columns. Is there a way to have integer or currency columns right aligned?
No. The closest I've seen is JustiCombo which is a database containing functions to center and right justify data for List and Combo Boxes. It can use proportional fonts by analysing the font attributes and character widths. It too stuffs spaces in the front of the fields to make the data appear centre/right justified. It did the best it could but you could see a few jaggies. But then maybe I was being too critical.
Depending on your query the alignment of a column will be inherited from the underlying table. So, go to the table, select the column, center/right/left align it, and then your textbox should have the same alignment. This won't work for calculated fields, but it should for most others.
As far as I'm aware, not in the traditional sense, no. I believe there are some third-party products that might be able to do this, but there's no native ColumnAlignment properties for listboxes in any versions I've used (haven't used Access 2007, though, for what it's worth).
Depending on how you are loading the listbox, you could use a fixed-width font (such as Courier) and left-pad your numbers with the appropriate number of spaces, to emulate right-alignment. It's not ideal, but it may be worth a shot.
Convert the listbox to combobox
Make the combobox that you converted right alignment
Convert it again to listbox
In VB it is:
Format(Format("10000", "0.00%"), "##########") where the number of "#"s are the width of the field in which to right justify the string.
In VBA you can use:
xFormat(Format("10000", "0.00%"), "##########") where
Function xFormat(ByVal s, ByVal width As String) As String
Dim temp As String
Dim deltaL As Integer
deltaL = Len(width) - Len(s)
If deltaL > 0 Then
temp = Space(deltaL) & s
Else
temp = s
End If
xFormat = temp
End Function
The way I solved it was by doing the following:
Go to File -> options -> Client settings -> General alignment
Change the settings to Text Mode, and it worked for me.
I use the following:
Public Function Paddy_Boy(ByVal s As String) As String
Const FillChar As Integer = 160 ' the key to success; this is an unpaddable space
Const MAX_CHARS As Integer = 12 ' the max # of chars in the target column; you could pass this as an arg, but obviously it depends on the data. and i can only get it to work nicely using Courier New.
Dim i As Integer
Dim l As Integer
Dim Z As String
Z = "Paddy_Boy"
Paddy_Boy = s
On Error GoTo Err_Sub
l = Len(s)
i = MAX_CHARS
While (i > l)
Paddy_Boy = Chr(FillChar) & Paddy_Boy
i = i - 1
Wend
Exit_Sub:
Exit Function
Err_Sub:
MsgBox Err.Number & ": " & Err.Description, vbCritical, Z
GoTo Exit_Sub
End Function