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.
Related
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.
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.
In Access, I have a form in which there are three textboxes.
I am trying to update a textbox called tbxCombinedName with a combination of both:
textbox tbxLastName (person's Last Name)
textbox tbxFirstName (person's First Name)
My question is: what textbox property do I use, so that as I am typing text in tbxLastName, the CombinedName textbox is updated immediately and thereafter saved in the table Contacts.
On Microsoft's website, I have found that the step processes when typing in a textbox are as follows:
KeyDown → KeyPress → BeforeInsert → Change → KeyUp
I've tried using the OnChange and OnKeyDown properties, but to no avail. Which property, combined with what code, will allow the update-as-you-type action to work?
This is what I wrote earlier, which didn't work:
Private Sub tbxLName_change()
Dim lastName As String
Dim nameCode As String
lastName = tbxLName.Value
Debug.Print lastName
nameCode = tbxNameCode.Value
nameCode = lastName
Debug.Print nameCode
End Sub
Thanks for all your help in advance.
This is one of the few cases where you should refer to the .text property.
In the Change event:
lastName = tbxLName.Text
The .text property is only available when a control has focus and it refers to the visible contents of the control.
However, this is a database and the general rule is that you no not store calculated fields. The full name can easily be obtained from a query.
Just a couple of notes:
You may want to go with KeyPress because it provides the ability to change or negate the key the user pushed.
In the example below, only letters are allowed and lower case letters are upper cased:
Private Sub tbxLName_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Const ASCII_LOWER_RANGE = 65
Const ASCII_UPPER_RANGE = 122
Const ASCII_LOWER_A = 97
Const ASCII_LOWER_Z = 122
Const UPPER_MODIFIER = -32
Const ASCII_CANCEL_CODE = 0
Select Case KeyAscii
Case ASCII_LOWER_RANGE To ASCII_UPPER_RANGE
If KeyAscii >= ASCII_LOWER_A And KeyAscii <= ASCII_LOWER_Z Then
KeyAscii = KeyAscii + UPPER_MODIFIER
End If
Case Else
KeyAscii = ASCII_CANCEL_CODE 'Cancel Key Press
End Select
End Sub
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.
Simple scenario: a form and one text box (unbound), Text1.
If "" <> Text1 Then
MsgBox "Not Empty"
End If
The above code works. The expression ""<> Text1 evaluates to True if the text box contain characters.
The opposite doesn't work, regardless of the text box is empty or not:
If "" = Text1 Then ' or alternatively, False = ("" <> Text1)
MsgBox "Empty!"
End If
Can you clarify this issue?
The textbox is usually null if it does not contain anything, this is not the same as a zero length string (""). It can often be best to use:
If Trim(Text1 & "") = vbNullString
'Empty
This will be true if the textbox contains spaces, a zero length string or null.
Alternatively, I've got a small function that I find useful for checking that sort of thing when dealing with various variable types and I just want to know whether it's blank.
'-----------------------------------------------------------------------------'
' True if the argument is Nothing, Null, Empty, Missing or an empty string. '
'-----------------------------------------------------------------------------'
Public Function IsBlank(arg As Variant) As Boolean
Select Case VarType(arg)
Case vbEmpty
IsBlank = True
Case vbNull
IsBlank = True
Case vbString
IsBlank = (arg = vbNullString)
Case vbObject
IsBlank = (arg Is Nothing)
Case Else
IsBlank = IsMissing(arg)
End Select
End Function
Just Made a blog post today about it too.
I always use the function Nz (variable, valueIfNull) to check those kind of things. For example:
if (Len(Nz(Me.txt1, "")) > 0) then
'Me.txt1 does not contain a value
end if
Or if I want to save a textbox's value to a recordset:
rst!Name = Nz(Me.txtName, "No name given")