Remove chars in a string until numeric is found in ASP and VB - string

I am trying to add to a page that someone else has written. I need to take a string that is formated with either 3 or 4 alpha characters followed by a series of numbers. I need to remove these alpha characters so that only a string of numbers is left.
Example:
What I'm string with is TrailerNumber = "CIN0012345"
and I need the result to be TrailerNumberTrimed = "0012345"
This is a web application written in an ASP (to be clear not ASPX) and VB page. This code will have to run on the server because it is being used as a search value in a database.

Not tested, but should work (assuming start of string is always 3/4 alpha followed by all numbers):
Dim TrailerNumberTrimed
If IsNumeric(Right(TrailerNumber, Len(TrailerNumber) - 4)) Then
TrailerNumberTrimed = Right(TrailerNumber, Len(TrailerNumber) - 4)
End If
If IsNumeric(Right(TrailerNumber, Len(TrailerNumber) - 3)) Then
TrailerNumberTrimed = Right(TrailerNumber, Len(TrailerNumber) - 4)
End If
' At this point, you should have the correct trimmed trailer number

Related

Filter phone numbers from open text field - Power BI, excel, VBA

I have a text field in a table where I need to substitute phone numbers where applicable.
For example the text field could have:
Call me on 08588812885 immediately
Call me on 07525812845
I need assistance please contact me
Good service
Sometimes a phone number will be in the text but not always and the phone number entered will always be different.
Is there a measure to use to replace the phone numbers with no text.
Ideally the solution would be Power BI, but can also be done in the raw data using excel or VBA
Regular expression in VBA (excel) or Python (Power BI) is a straightforward solution.
I have never used PowerBI with Python before but manage to make following python script.
In PowerBI transformation steps I created a new column that would copy [message] columns and named it [noPhoneNumber], then next step ran this python script
import re
def removePhone(x):
return re.sub('\d{10,11}', "**number removed**", x)
length = len(dataset["noPhoneNumber"])
for iRow in range(length):
dataset["noPhoneNumber"][iRow] = removePhone(dataset["noPhoneNumber"][iRow])
so column "noPhoneNumber"
Call me on 08588812885 immediately
Call me on 07525812845
I need assistance please contact me
Good service
becomes
Call me on **number removed** immediately
Call me on **number removed**
I need assistance please contact me
Good service
In VBA Preferable create UDF (user defined function) and don't create a subroutine, that would be too error prone for this kind of problem.
[Added]
If you need to make a Excel based solution, you can create a UDF function like so:
(remember early binding to import of VBScript_RegExp_55.RegExp in excel)
Function removePhoneNumber(text As String, Optional replacement As String = "**number removed**") As String
Dim regex As New RegExp
regex.Pattern = "\d{10,11}"
removePhoneNumber = regex.Replace(text, replacement)
End Function
...and then use excel function like so:
=removePhoneNumber(A2),
=removePhoneNumber(A3)
and so on...
A simple VBA function alternative
Function removePhone(s As String) As String
Const DELIM As String = " "
Dim i As Long, tokens As Variant
tokens = Split(s, DELIM)
For i = LBound(tokens) To UBound(tokens)
If IsNumeric(tokens(i)) Then
tokens(i) = "*Removed*" ' << change to your needs
Exit For ' assuming a single phone number per string
End If
Next
removePhone = Join(tokens, DELIM)
End Function
You can do this in Power Query. Create a custom column with this below code. I have considered the column name is Comments but please adjust this with your column name.
if Text.Length(Text.Select([comments], {"0".."9"})) = 11
then
Text.Replace(
[comments],
Text.Select([comments], {"0".."9"}),
""
)
else [comments]
Here is the output below. You can also replace phone numbers with other text like #### to make is anonymous.
NOTE
This will only work if there are only 1 number in the string with length 11 (You can adjust the length in code as per requirement).
This will Not work if there are more than one Numbers in the string.
If there are 1 number in the string but length not equal 11, this will keep the whole string as original.

Dividing two text string with option strict on

Can you please help me to get the best method for dividing two text string with option strict on
If TxDovizAlisAlt1.Text <> "" Then
TxOranUst.Text = Math.Round(TxDovizAlisAlt2.Text / TxDovizAlisAlt1.Text, 4)
End If
Text string are retrieving from a web page either with "." or "," decimal sembol
Since you have text (string) inside textbox, you first have to convert that text to actual number.
Without knowing what the actual data is in them I'll be vague and say that you can use something like TryParse, Cast or Convert.
For example:
Math.Round(CDbl(TxDovizAlisAlt2.Text) / CDbl(TxDovizAlisAlt1.Text), 4)
Dim test As Double = Math.Round(CDbl("123.456") / CDbl("78.910"), 4)
Debug.Print(test.ToString) 'Print>>> 1.5645

Splitting a string of a multiline textbox by lines

I want to split the text of a textbox after a specific amount of visible lines.
I've found some codes that "allows that", but all of them consider the lines by the "vbCrLf" parameter, but i want to split using the visible lines of a multiline textbox.
To make it more clear to understand, consider a multiline textbox with the following text:
"The history of textbooks dates back to civilizations of ancient history. For example, Ancient Greeks wrote texts intended for education. The modern textbook has its roots in the standardization made possible by the printing press. Johannes Gutenberg himself may have printed editions of Ars Minor, a schoolbook on Latin grammar by Aelius Donatus. Early textbooks were used by tutors and teachers, who used the books as instructional aids (e.g., alphabet books), as well as individuals who taught themselves."
When i use the Textbox.Linecount function it returns the number 6 because the textbox shows six lines (which depends on the size of the control), but if i use a function like strText = Split(TextBox.Text, vbCrLf) it will return 1, because there is only one vbCrLf. But i need to split the text into two textbox considering the visible lines of the control, something like what happens in page breaks of MS Word.
For a better visual explanation, please look at the attached image.
Example
Firstly, I'm not convinced there is a robust and elegant way to do this, but it was fun to experiment and it might be useful to you.
The following will split the contents of TextBoxInput into TextBoxPage1 and TextBoxPage2 breaking on the line number specified by PAGED_TEXT_BOX_LINES.
It uses the textbox itself to detect natural line breaks and thus implicitly caters for the size of the textbox, the font, etc.
The desired line count is hard coded as a constant - not doing this would require an alternative of calculating the line height of the textbox (requiring calculations based on the font metrics and the textbox's internal line-leading size).
It only handles two "pages". But the concept could be extended simply by repeating the process based on the remainder of text that ends up in TextBoxPage2.
Private Sub CommandButton1_Click()
Const PAGED_TEXT_BOX_LINES As Integer = 5
Dim text As String
Dim i As Long
Dim textLength As Long
Dim curLine As Integer
text = TextBoxInput.text
textLength = Len(text)
TextBoxPage1.SetFocus
'add characters of the input string until the first page textbox
' exceeds maximum line count
For i = 1 To textLength
TextBoxPage1.text = Mid$(text, 1, i)
If TextBoxPage1.LineCount > PAGED_TEXT_BOX_LINES Then
'retreat cursor until we reach previous line, so we can
' detect the word that wrapped
curLine = TextBoxPage1.curLine
Do While TextBoxPage1.curLine = curLine
TextBoxPage1.SelStart = TextBoxPage1.SelStart - 1
Loop
'the remaining text after the SelStart is what
' wrapped, so stop page 1 after SelStart
TextBoxPage1.text = Mid$(text, 1, TextBoxPage1.SelStart)
TextBoxPage2.text = Trim$(Mid$(text, TextBoxPage1.SelStart + 1))
Exit For
End If
Next i
End Sub

VBA Special characters U+2264 and U+2265

I have a frustrating problem. I have a string containg other characters that are not in this list (check link). My string represents a SQL Query.
This is an example of what my string can contain: INSERT INTO test (description) VALUES ('≤ ≥ >= <=')
When I check the database, the row is inserted successfully, but the characters "≤" and "≥" are replaced with "=" character.
In the database the string in description column looks like "= = >= <=".
For the most characters I can get a character code. I googled a character code for those two symbols, but I didn't find one. My goal is to check if my string contains this two characters , and afterwards replace them with ">=" and "<="
===Later Edit===
I have tried to check every character in a for loop;
tmp = Mid$(str, i, 1)
tmp will have the value "=" when my for loop reaches the "≤" character, so Excel cannot read this "≤" character in a VB string, then when I'm checking for character code I get the code for "=" (Chr(61))
Are you able to figure out what the character codes for both "≤" and "≥" in your database character set are? if so then maybe try replacing both characters in your query string with chrw(character_code).
I have just tested something along the lines of what you are trying to do using Excel as my database - and it looks to work fine.
Edit: assuming you are still stuck and looking for assistance here - could you confirm what database you are working with, and any type information setting for the "description" field you are looking to insert your string into?
Edit2: I am not familiar with SQL server, but isn't your "description" field set up to be of a certain data type? if so what is it and does it support unicode characters? ncharvar, nchar seem to be examples of sql server data types that support Unicode.
It sounds like you may also want to try and add an "N" prefix to the value in your query string - see
Do I have use the prefix N in the "insert into" statement for unicode? &
how to insert unicode text to SQL Server from query window
Edit3: varchar won't qualify for proper rendering of Unicode - see here What is the difference between varchar and nvarchar?. Can you switch to nvarchar? as mentionned above, you may also want to prefix the values in your query string with 'N' for full effect
Edit4: I can't speak much more about sqlserver, but what you are looking at here is how VBA displays the character, not at how it actually stores it in memory - which is the bottom line. VBA won't display "≤" properly since it doesn't support the Unicode character set. However, it may - and it does - store the binary representation correctly.
For any evidence of this, just try and paste back the character to another cell in Excel from VBA, and you will retrieve the original character - or look at the binary representation in VBA:
Sub test()
Dim s As String
Dim B() As Byte
'8804 is "≤" character in Excel character set
s = ChrW(8804)
'Assign memory representation of s to byte array B
B = s
'This loop prints "100" and "34", respectively the low and high bytes of s coding in memory
'representing binary value 0010 0010 0110 0100 ie 8804
For i = LBound(B) To UBound(B)
Debug.Print B(i)
Next i
'This prints "=" because VBA can not render character code 8804 properly
Debug.Print s
End Sub
If I copy your text INSERT INTO test (description) VALUES ('≤ ≥ >= <=') and paste it into the VBA editor, it becomes INSERT INTO test (description) VALUES ('= = >= <=').
If I paste that text into a Excel cell or an Access table's text field, it pastes "correctly".
This seems to be a matter of character code supported, and I suggest you have a look at this SO question.
But where in you program does that string come from, since it cannot be typed in VBA ??
Edit: I jus gave it a try with the below code, and it works like a charm for transferring your exotic characters from the worksheet to a table !
Sub test1()
Dim db As Object, rs As Object, cn As Object
Set cn = CreateObject("DAO.DBEngine.120")
Set db = cn.OpenDatabase("P:\Database1.accdb")
Set rs = db.OpenRecordset("table1")
With rs
.addnew
.Fields(0) = Range("d5").Value
.Update
End With
End Sub

Formatting strings in a text field in Crystal Reports XI

Good morning!
I'm hoping someone can help me with what is probably a simple question but I just cant get things to work the way I would like. I am currently working with a report that has a "catch-all" text field. In this field the user can input anything they want, and on occasion, will input information in a column format (ex. 1.1). This field allows carriage returns which are used to create "rows" in this field. The problem is that the user wants the "columns" in this field to line up on the report without having to count spaces between the columns when the information is entered (ex. 1.2). The problem is that even when this type of information is entered there is no set protocol or formatting guidelines. There may be multiple "subtitles", rows, rows separated by subtitles, etc.. The carriage return (Chr(10)) at the end of each line (or beginning of each new line) is the only thing that can be relied on consistantly.
I am currently trying to seperate each individual row, format each as desired, and put it back together like so:
Dim output As String
Dim sections as String
Dim returnCount as Int
Dim leftText as String
Dim rightText as String
Dim sectionTogether as String
Dim totalText as String
Dim textLength as Int
output = {table.textfield}
sections = ExtractString(output, Chr(10), Chr(10))
If Instr(sections," ") > 0 Then
leftText = Left(sections, Instr(sections, " "))
textLength = Length(Left(sections, Instr(sections, " "))
rightText = Right(sections, Instr(sections, " "))
Replace(sections," "," ")
sectionTogether = rightText + (Space(20) - (textLength - 3)) + leftText
totalText = totalText + sectionTogether
formula = totalText
else
formula = output
This is the gist of what I'm trying to do. A couple of notes:
1) I know I am missing a loop of some kind to format every section but I dont know how to set that up in crystal
2) I have VB programming experience, but I am noob in crystal and its limited tools so I feel hamstringed and I'm having trouble finding the methods and tools I would use in Visual Studio
3) My syntax may also be off in a few places because I am still learning how to set this up and I REALLY miss a debugger.
I hope someone can help me, I have been researching for over a week and it feels like I'm just beating my head against a wall.
Thank you in advance.
The output examples
ex. 1.1
"Your current charges are:
Jan 12.89
Feb 117.44
Mar 15.02
Apr 4.17"
ex. 1.2
"Your current charges are:
Jan 12.89
Feb 117.44
Mar 15.02
Apr 4.17"
The first thing you're going to want to do is split up your rows via split(), like this:
local stringvar array wallOText := split({table.textfield},chr(10));
This will give you an array of strings where each array entry is a "row". Now you can loop over your rows with the following:
for i := 1 to ubound(wallOText) step 1 do <some stuff to wallOText[i]>
Now, getting the columns right-justified is a little trickier, but here's some code to get you started. You can adjust the column widths to whatever you may need (in this case, 20 spaces). Also note, you have to use a fixed-width font.
local stringvar output;
local stringvar array row;
local numbervar i;
local numbervar j;
local stringvar array wallOText := split({#some text},chr(10));
local stringvar elem;
for i := 1 to ubound(wallOText) do //loop over lines
(row := split(wallOText[i]," ");
for j := 1 to ubound(row) do //loop over words
(elem := trim(row[j]); //get current element and cut white space
if not(elem="") then
output := output + space(20-len(elem)) + elem); //build output string
output := output + chr(10));
output

Resources