Text.remove for phone number formatting in vb.net - vb.net

I have a textbox for a phone number that formats the phone number to look like this:
(123) 456-7891
but I want it to change back to just numbers when the user is finished with the data entry:
1234567891
Here's my code for formatting the number:
Dim newNumber As String
If txtContactNumberNew.Text.Length = 0 Then
txtContactNumberNew.Text = "N/A"
ElseIf txtContactNumberNew.Text.Length = 10 Then
newNumber = "(" & txtContactNumberNew.Text.Substring(0, 3) & ") " & txtContactNumberNew.Text.Substring(3, 3) & "-" & txtContactNumberNew.Text.Substring(6, 4)
txtContactNumberNew.Text = newNumber
ElseIf txtContactNumberNew.Text.Length > 10 Then
newNumber = "(" & txtContactNumberNew.Text.Substring(0, 3) & ") " & txtContactNumberNew.Text.Substring(3, 3) & "-" & txtContactNumberNew.Text.Substring(6, 4) & " x " & txtContactNumberNew.Text.Substring(10)
txtContactNumberNew.Text = newNumber
ElseIf txtContactNumberNew.Text.Length < 10 Then
MsgBox("Not enough Numbers! Please retype the Phone number", vbExclamation, "Not enough Numbers")
Return
End If
Since I added the parenthesis would this change my character count? I just want the formatting removed when the form is completed.

Consider using the trim method to remove unwanted characters. You could then get the character count of the result.
'List of characters to remove
Dim charsToTrim() As Char = { "("c, ")"c, "-"c}
Dim result As String = txtContactNumberNew.Text.Trim(charsToTrim)
taken from http://msdn.microsoft.com/en-us/library/d4tt83f9.aspx

if you just want the () removed can't you just use replace from regex
System.Text.RegularExpressions.Regex.Replace(str,"[\(|\)|\-|\s]","")

Related

Excel+VBA: Userfrom string Deal(Order) Number parsing

I am trying to make a full function report file which connects to old version access data base. I need to build a Userform where user can enter deal (order) number just like we can add pages in print dialog box.
So far I have found below question which has given me partial answer:
How to Parsing Full String and split into several String in Excel VBA?
I can use Split(string) method to get various deal numbers when separated by ",".
However, I also need From to TO deal number option as well.
so, if user enters on String1 = "10001 - 10050, 20111 , 20115"
then I need output as
Deal_Line.Deal_Number >= 10001 and Deal_Line.Deal_Number <= 10050
and Deal_Line.Deal_Number = 20111 and Deal_Line.Deal_Number = 20115.
I can refine SQL String for my requirement, I would like to know if there is a way to use two deliminator.
Expanding on #user3598756 answer, (which does exactly what you asked for) and interpreting your requirements I come up with the following:
Function ProcessString(strng1 As String, fieldname As String) As String
Dim sqlStrng As String
Dim strng As Variant, limits As Variant
For Each strng In Split(strng1, ",")
limits = Split(strng, "-")
If UBound(limits) = 0 Then
sqlStrng = sqlStrng & "[FIELD] = " & limits(0) & "|"
Else
sqlStrng = sqlStrng & "([FIELD] >= " & Trim(limits(0)) & " And [FIELD] <= " & Trim(limits(1)) & ")|"
End If
Next
ProcessString = Replace(WorksheetFunction.Trim(Join(Split(Left(sqlStrng, Len(sqlStrng) - 1), "|"), " Or ")), "[FIELD]", fieldname)
End Function
The test line would be:
MsgBox ProcessString("10001 - 10050, 20111 , 20115","Deal_Line.Deal_Number")
This will produce an output that I think is more likely to be what you actually want - using OR instead of AND for starters, adding in parentheses needed for the OR to work properly and allowing for multiple table/field names.
Then again, maybe I've misinterpreted your requirement - I just can't see what use having all AND would be one one field.
you could use this helper function:
Function ProcessString(strng1 As String) As String
Dim sqlStrng As String
Dim strng As Variant, limits As Variant
For Each strng In Split(strng1, ",")
limits = Split(strng, "-")
If UBound(limits) = 0 Then
sqlStrng = sqlStrng & "Deal_Line.Deal_Number = " & limits(0) & "|"
Else
sqlStrng = sqlStrng & "Deal_Line.Deal_Number >= " & limits(0) & " And Deal_Line.Deal_Number <= " & limits(1) & "|"
End If
Next
ProcessString = WorksheetFunction.Trim(Join(Split(Left(sqlStrng, Len(sqlStrng) - 1), "|"), " And "))
End Function
to be tested/expolited in your "main" code as:
Sub main()
MsgBox ProcessString("10001 - 10050, 20111 , 20115")
End Sub

word vba - remove manually typed list number

I have lot of documents with list number typed manually, so my intent is to remove those manual list number and the tab or space following it.
e.g
1. Text 1
1.1 Text 2
1.1.1 Text 3
1.1.1.1 Text 4
become
Text 1
Text 2
Text 3
Text 4
I'm not sure how to do this with vba and I'd really appreciate your help.
I have figured it out by using below code:
Sub RemoveManualListNumber()
Dim strInitialPar As String
Dim intSpace As Integer, intTab As Integer
Dim strFinalPar As String
Dim iPar
For iPar = 1 To ActiveDocument.Paragraphs.Count
strInitialPar = ActiveDocument.Paragraphs(iPar).Range.Text
intSpace = InStr(1, strInitialPar, " ")
intTab = InStr(1, strInitialPar, Chr(9))
Debug.Print "Paragraph " & iPar & ": " & "Index space = " & intSpace & ", Index tab = " & intTab
If intTab > 0 And intTab < intSpace Then
strFinalPar = Right(strInitialPar, Len(strInitialPar) - intTab)
Else
strFinalPar = Right(strInitialPar, Len(strInitialPar) - intSpace)
End If
ActiveDocument.Paragraphs(iPar).Range.Text = strFinalPar
Next iPar
End sub

VBA ACCESS Comparing String as they are integer

I am trying to prompt the user to input a range and display all the instruments that are within that range in a subform.
Problem: The upper and lower range is a text field (because some of the range cannot be expressed in integer). As seen in the screenshot, the comparison only compare the first character of the field.
User's input: 5 - 3
On the subform: 36 - 4
It compares 5 and 3 instead of 36
I know vba is doing what it has been told but how can I achieve the result I want?
Here is my code for requering the subform:
Dim Up As Integer
Dim Low As Integer
If Me.Text_L = "" Or IsNull(Me.Text_L) Or Me.Text_U = "" Or IsNull(Me.Text_U) Then
MsgBox ("Please choose a valid range!")
Else
Up = Me.Text_U
Low = Me.Text_L
SQL = SQL_Origin & " WHERE [qry_View_Search].[Upper_Range] <= '" & Up & "' " _
& "AND [qry_View_Search].[Lower_Range] >= '" & Low & "';"
subform_View_Search.Form.RecordSource = SQL
subform_View_Search.Form.Requery
End If
so what i did is made a new column in the query for
IIf(IsNumeric([Upper]), Val([Upper]), Null)
to get all the numeric result.
Then in the vba, I re query the subform as below
SQL = SQL_Origin & " WHERE [qry_View_Search].[Upper] <= cint(Forms![frm_View_Search]![Text_U]) " _
& "AND [qry_View_Search].[Lower] >= cint(Forms![frm_View_Search]![Text_L]);"
Thanks #HansUp !
I have successfully for those cases used Val only:
Value: Val([FieldName])
or:
Value: Val(Nz([FieldName]))

VBA function to convert name format

I want to take a name in First Last format and change it to Last, First. I know I could to this with a formula but I want to be complicated.
Please let me know if you see any red flags in my code, or suggestions for improvements.
Function LastFirst(Name_FL As String)
'This only works if there is a single space in the cell - Will Error If Spaces <> 1
Length = Len(Name_FL) 'Establishes Length of String
Spaces = Length - Len(Application.WorksheetFunction.Substitute(Name_FL, " ", "")) 'Number of spaces
If Spaces <> 1 Then
LastFirst = "#SPACES!#" 'Error Message
Else
SpaceLocation = Application.WorksheetFunction.Find(" ", Name_FL, 1) 'Location of space
Last = Right(Name_FL, Length - SpaceLocation) 'Establishes Last Name String
First = Left(Name_FL, SpaceLocation) 'Establishes First Name String
LastFirst = Application.WorksheetFunction.Proper(Last & ", " & First) 'Puts it together
End If
End Function 'Ta-da
You could simplify it to:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) > 1 Then
LastFirst = "#SPACES#"
Else
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
End If
End Function
The logic here is:
If there is more than 1 space, return the error string #SPACES#
If there is 1 space, the split the string using " " as a delimiter.
Use the second index of the Split array, add ", " and use the first index of the split array.
Use StrConv() to convert it all to proper case.
You might also want to add another check for no spaces:
If InStr(Name_FL, " ") > 0 Then
'// There is a space in the string
Else
'// There is no space in the string
End If
Which can also be tested for by slightly changing the logic of the above example:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) = 1 Then
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
Else
LastFirst = "#SPACES#"
End If
End Function
Further elaboration on functions:
You can see I've used some VBA functions here in place of your WorksheetFunction methods.
Len() returns the Length of a string.
Replace() does what it says on the tin - replaces a given string with another.
StrConv() Converts a String to a respective case (e.g. vbProperCase).
Split() Creates a zero-based single dimension array from a string, by Splitting it on a given delimiter.
Finally - Don't forget to specify a return value in your function header:
Function LastFirst(Name_FL As String)As String<~~ return type

Check if a string variable has an integer value

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)
A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If
Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then
You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.
IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub
Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian
Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If
Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer
In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN