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.
Related
Is it possible to remove the first few lines of multiple records in a Rich Text Long Text field in access? Thanks.
Obviously, you can, as you can do many string manipulations in Access.
Try to show some research and attempts next time.
You can use the following function to remove lines from strings:
Public Function RemoveLines(str As String, LineCount As Integer) As String
Dim searchPosition As Integer
searchPosition = 1
Dim linesPassed As Integer
linesPassed = 0
Dim Found As Integer
Found = 1
Do While linesPassed < LineCount
Found = InStr(searchPosition, str, vbCrLf)
If Found <> 0 Then
searchPosition = Found + 2
Else
RemoveLines = ""
Exit Function
End If
linesPassed = linesPassed + 1
Loop
RemoveLines = Mid(str, searchPosition)
End Function
This removes LineCount lines from your string. You can either use it in VBA or in action queries, though rich text memo fields in action queries tend to start with a single linebreak, and have all line breaks repeated. If you just enter twice the amount you actually want to remove, it will work in action queries.
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.
I have problem with text box named "txtPrice". I want to protect this text box from a string. If we input one string it will show message that I wrote. But if I input, for example "12r", it doesn't do anything.
Dim i As Integer
Dim s As Long
i = Asc(txtPrice)
If i < 48 or i> 57 then 'ascii number
MsgBox "Error"
End If
What exactly are you looking for? Under properties you can specify an input mask.
You can try If Not IsNumeric(txtPrice) if you're looking for a number.
If you don't want any letters, try this:
Dim intPos As Integer
For intPos = 1 To Len(txtPrice)
Select Case Asc(Mid(txtPrice, intPos, 1))
Case 65 To 90, 97 To 122
IsLetter = True
Case Else
IsLetter = False
End Select
If IsLetter Then Exit For
Next intPos
If IsLetter Then
MsgBox "Error"
End If
You can also do this within the properties of the text box field using validation rules:
https://support.office.com/en-gb/article/Restrict-data-input-by-using-validation-rules-b91c6b15-bcd3-42c1-90bf-e3a0272e988d
You can restrict data entry in this way. For instance you could enter >=0 in the validation rules property and then "Please enter numbers only" in the validation text property. I have used both methods (vba as previous answer) and access validation rules and both work well.
What started as a simple validation code converted in something very paradoxical in my eyes.
The following code returns "Good work!" when I input a negative number in the InputBox popup
Dim myvar As String
myvar = InputBox("input a positive number, please")
If IsNumeric(myvar) Then
myvar = CDbl(myvar)
Select Case myvar
Case Is < 0
MsgBox "I need a positive number"
Exit Sub
Case Is > 0
MsgBox "Good work!"
[MyField] = myvar
RunCommand acCmdSaveRecord
Me.Requery
Exit Sub
Case Else
MsgBox "You entered '" & myvars & "'. I don't know what to do about"
End Select
Else
MsgBox "A Number, please"
End If
Is this really the best way to validate an InputBox?
Since myvar is a String, CDbl(myvar) will get implicitly converted back to a string. Create a temporary numeric variable for the Select Case.
I agree with some of the other answers. Think about this code re-write (notice the second variable declared):
Dim myvar as String
Dim myDbl as Double
myvar = inputBox ("Input a positive number, please")
if isnumeric(myvar) then
myDbl = cDbl(myvar)
else
msgbox "Enter a number please"
exit sub
end if
if mydbl <=0 then
msgbox "I need a positive number"
else 'if mydbl > 0 then
MsgBox "Good work!"
[MyField] = myvar
RunCommand acCmdSaveRecord
Me.Requery
end if
That would solve you problems by accounting for zero and declaring a separate variable as a double there. The if statement instead of the case is just preference I suppose. But now think about the two variables you have.
debug.print "MyVar is a string containing: " & myvar
debug.print cstr(cdbl(myvar)*2)
'This forces myvar into a double(a number-type) to do math on it and then print it out
However, if you were to re-run the first print, you would see that myvar is still a string and can be used like a string. In VBA, unlike some other languages, variables are only what you declare them as. If you want to use them as other things, you have to declare another variable of the needed type.
TL;DR Think of them as different containers. Strings are circle boxes and doubles are square boxes. They might be able to hold similar stuff but the functionality of the containers is limited by their shape. In VBA you don't have a way to force a circle into a square so you have to make a whole second container and transfer the stuff over.
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