Extract char/numbers using Mid and Pos function - function

I have a string with a value of "String_test|123456"
How can I extract the numbers and characters and put them to another variable
string2 = "String_test" and int = 123456 using Mid / Pos functions.
Thanks!

Assuming you want a PowerBuilder answer rather than the ones given...
You seem to have a string with a 'string' portion and a 'number' portion delimited by a pipe character '|'. Assuming this is the normal format of the data you find the position of the pipe by:
li_pipepos = Pos(ls_string, '|')
Then the string portion is found thusly:
ls_string_portion = Mid(ls_string, 1, li_pipepos - 1)
The number portion is found:
ls_number_portion = Mid(ls_string, li_pipepos + 1 )
Then you convert the number portion into an integer (watch out since in PB an integer is not very large - i'd use a long instead) by:
ll_number = Long(ls_number_portion)
Now if your data isn't in a standardized format you will need to loop through all the characters to determine if they are a number or not and then append them to a string variable (one for numbers and another for characters) then finally convert the number string into a number.

Assuming | is the delimiter, it's easier to use Split function to do this.
Sub Test()
Const sampleStr As String = "String_test|123456"
Dim splitArr() As String
splitArr = Split(sampleStr, "|")
Dim string2 As String
string2 = splitArr(0)
Debug.Print string2 'String_test
Dim int2 As Long
int2 = splitArr(1)
Debug.Print int2 '123456
End Sub

You can modify this user defined function to suit your needs.
Public Function ReturnIntegers(cell As Range) As String
Dim stringholder As String
stringholder = cell.value
Dim pos As Integer
pos = InStr(1, stringholder, "|", vbTextCompare)
ReturnIntegers = Right(stringholder, (Len(stringholder) - pos))
End Function

Related

VBA - How Can I Get Randomize String Array To Work?

Overview: I am pasting many words on separate lines into text box: txtWordRandomizer. Then, move each line into the string array. I need to shuffle/randomize the array, but can't seem to get it to work.
I got the bottom Sub, ShuffleArray(), here: http://www.cpearson.com/excel/ShuffleArray.aspx
...and it seems to be what everyone references when talking about shuffling/randomizing an array.
I get Error: Type Mismatch: array or user-defined type expected on calling ShuffleArrayInPlace(), but thought this was for randomizing a string array. Do I somehow need to translate the string array into a variant array?
Or, any other suggestion on how I can get this to work?
Private Sub btnRandomize_Click()
Dim strRandoms() As String
strRandoms() = Split(Me.txtWordRandomizer.Value, vbCrLf)
strRandoms() = ShuffleArray(strRandoms())
End Sub
Function ShuffleArray(InArray() As Variant) As Variant()
' This function returns the values of InArray in random order. The original
' InArray is not modified.
Dim N As Long
Dim Temp As Variant
Dim J As Long
Dim Arr() As Variant
Randomize
L = UBound(InArray) - LBound(InArray) + 1
ReDim Arr(LBound(InArray) To UBound(InArray))
For N = LBound(InArray) To UBound(InArray)
Arr(N) = InArray(N)
Next N
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
Temp = InArray(N)
InArray(N) = InArray(J)
InArray(J) = Temp
Next N
ShuffleArray = Arr
End Function
Based on some quick testing, the ShuffleArray function in the posted link doesn't actually return a randomized array. Since you're keeping your array in the strRandoms variable, you can use the in-place function anyways (the in-place function will also be more efficient, since it doesn't have to create and populate an entirely new array when called).
When calling the function and passing your array as an argument, don't include parentheses after your array. So do this:
ShuffleArrayInPlace a
' Or this:
Call ShuffleArrayInPlace(a)
However, in order to do this successfully, you have to slightly change the method signature of ShuffleArrayInPlace from this (as it is now):
Sub ShuffleArrayInPlace(InArray() As Variant)
to this:
Sub ShuffleArrayInPlace(InArray As Variant)
Note that the parentheses after the InArray are gone. Why do this?
Originally, with the parentheses, the function is expecting an array of Variant values. However, the split function returns an array of string values. By changing the method signature to remove the parentheses, you're basically saying you can pass anything to the function (a string array, a variant array, or even something that's not an array at all). Because of this, you could update ShuffleArrayInPlace to raise an error if the argument is not an array (using the IsArray function).
Speaking of refactoring: While the algorithm the ShuffleArrayInPlace uses to shuffle an array is clear, it's not necessarily the best one. I would review the Fisher-Yates shuffle, and try implementing it yourself in VBA as an exercise.
So, in summary...
When calling a function that takes an array as an argument, don't put parentheses after the array: `Call ShuffleArrayInPlace(strRandoms)
Use ShuffleArrayInPlace, not ShuffleArray.
Change the ShuffleArrayInPlace function so that InArray is a Variant, not Variant().
This works for me:
Private Sub btnRandomize_Click()
Dim strRandoms() As String
strRandoms = Split("A|B|C|D|E", "|")
strRandoms = ShuffleArray(strRandoms)
Debug.Print Join(strRandoms, ", ")
End Sub
Function ShuffleArray(InArray() As String) As String()
Dim N As Long, Temp As Variant
Dim J As Long, Arr() As String
Randomize
'make a copy of the array
ReDim Arr(LBound(InArray) To UBound(InArray))
For N = LBound(InArray) To UBound(InArray)
Arr(N) = InArray(N)
Next N
'shuffle the copy
For N = LBound(Arr) To UBound(Arr)
J = CLng(((UBound(Arr) - N) * Rnd) + N)
Temp = Arr(N)
Arr(N) = Arr(J)
Arr(J) = Temp
Next N
ShuffleArray = Arr 'return the shuffled copy
End Function

Get rid of any parenthesis or values enclosed in parenthesis SSRS

I'm trying to remove any parenthesis or value enclosed in parenthesis in a string field in SSRS, which will be the best way to do it? I read about replace function but not sure how to use it with several values.
Here are some examples about what I'm trying to do:
Original string Expected string
ERP(123) ERP
TE(PO)ST TEST
(123)string string
Assuming you only have a single set of parentheses then this will work.
=LEFT(Fields!test.Value, InStr(Fields!test.Value, "(") -1)
&
MID(Fields!test.Value, InStr(Fields!test.Value, ")") +1)
Basically we take the left part of the string up to the first "(" position minus 1
and then concatenate the remainder of the string starting at the first ") +1
For this I would use a function that would be usable everywhere and not always copy paste:
In here we do a Substring of the part we want to delete, and then we do a Replace to changed with no spaces and that way the string will be together (in the case if the original was separated by the parenthesis)
Public Function removeParenthesis (input As Object) As Object
Try
Dim FirstIndex As Integer = input.IndexOf("(")
Dim SecondIndex As Integer = input.IndexOf(")") - FirstIndex + 1
Dim Result As String = input.ToString().Replace(input.Substring(FirstIndex, SecondIndex), "")
Return Result
Catch ex As Exception
Return ex
End Try
End Function
This is pasted in the Code sections and will be called like this:
Code.removeParenthesis(Fields!Textbox1.Value)
The function is implemented on Report > Report Properties > Code > paste the function above
EDIT
Taking in mind what #Alan Schofield said in his answer
Assuming you only have a single set of parentheses [...].
I have made a little change and have validate too if there's actually some parenthesis, the idea is to loop till everything is clean.
If there's no parenthesis then It'll return original value
Public Function removeParenthesis(input As Object) As Object
Try
Dim Result As String = input.ToString()
Dim FirstIndex As Integer = Result.IndexOf("(")
Dim SecondIndex As Integer = Result.IndexOf(")")
While FirstIndex <> -1 And SecondIndex <> -1
SecondIndex = SecondIndex - FirstIndex + 1
Result = Result.Replace(Result.Substring(FirstIndex, SecondIndex), "")
FirstIndex = Result.IndexOf("(")
SecondIndex = Result.IndexOf(")")
End While
Return Result
Catch ex As Exception
Return ex
End Try
End Function

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

extract numbers from string in access

I need help creating a VB code or expression in Access 2010 that will group numbers from a string where each set starts with number 6 and is always 9 characters long.
Example of strings:
Order Confirmation # 638917872-001 Partial Order/$23.74 RECEIVED
Order Confirmation - Multiple Orders - Order Confirmation#639069135-001/$297.45 - Order Confirmation#639069611-001/$32.08.
I'm using a VB code to remove all the alpha characters but that just leaves me with:
6389178720012374 from string 1 and
639069135001297456390696110013208 from string 2.
All I care about is the order number that starts with 6 and is 9 characters long. Any help would be greatly appreciated, I know there's an easier way.
VB.NET Solution:
If you just need the first 9 numbers from your resulting strings you could use String.Substring, ie:
Dim numberString as String = "6389178720012374"
Dim newString As String = numberString.Substring(0, 9)
MessageBox.Show(newString)
shows 638917872
MSDN Link
EDIT:
Maybe you would want to use a RegEx - something like this perhaps can get you started:
Private Sub Input()
Dim numberString As String = "Order Confirmation # 638917872-001 Partial Order/$23.74 RECEIVED"
Dim numberString2 As String = "Order Confirmation - Multiple Orders - Order Confirmation#639069135-001/$297.45 - Order Confirmation#639069611-001/$32.08"
GiveMeTheNumbers(numberString)
GiveMeTheNumbers(numberString2)
End Sub
Function GiveMeTheNumbers(ByVal s As String) As String
Dim m As Match = Regex.Match(s, "6\d{8}") 'get 9 digit #s begin w/6
Do While m.Success
MessageBox.Show(m.Value.ToString)
m = m.NextMatch()
Loop
Return False
End Function
Results -
MessageBox1: 638917872
MessageBox2: 639069135
MessageBox3: 639069611
You can use this function ... tested in VB.NET
Function NumOnly(ByVal s As String) As String
sRes = ""
For x As Integer = 0 To s.Length - 1
If IsNumeric(s.Substring(x, 1)) Then sRes = sRes & s.Substring(x, 1)
Next
return sRes
End Function
Little modif for ms-access
OK, here's a VBA solution. You'll need to add Microsoft VBScript Regular Expressions to your references.
This will match every 9 digit number it finds and return an array of strings with the order #s.
Function GetOrderNum(S As String) As String()
Dim oMatches As Object
Dim aMatches() As String
Dim I As Integer
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
ReDim aMatches(0)
RE.Pattern = "\d{9}"
RE.Global = True
RE.IgnoreCase = True
Set oMatches = RE.Execute(S)
If oMatches.Count <> 0 Then
ReDim aMatches(oMatches.Count)
For I = 0 To oMatches.Count - 1
aMatches(I) = oMatches(I)
Next I
End If
GetOrderNum = aMatches
End Function

SSRS how to decode foreign language characters

I'm passing this string to a report: Economia e Administração
But the report displays the following: Economia e Administração
In the URL it gets encoded as:
Economia%20e%20Administra%C3%83%C2%83%C3%82%C2%A7%C3%83%C2%83%C3%82%C2%A3o%20
I tried using URLDecode, but it doesn't work.
Any ideas?
Thanks!
It looks like it's being converted into UTF-8 twice, ie, an encoded string is being encoded again. Is the original string being passed as Unicode or UTF-8 or something else?
CORRECTION: it's converted into UTF-8 three times!
Here's my solution...In parent report convert the string to a Byte array string and pass that to the child report:
Function GetStringBytes(ByVal theString As String) As String
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(theString, 0, theString.Length)
Dim builder As New System.Text.StringBuilder
For Each i As Integer In bytes
builder.Append(i & "|")
Next i
Return builder.ToString().TrimEnd("|")
End Function
In the Child report pass the byte array string to the GetString function below to convert it back to the original string:
Function GetString(ByVal theBytes As String) As String
Dim byts() As Byte = New Byte(theBytes.Split("|").Length) {}
Dim count As Integer = 0
For Each i As String In theBytes.Split("|")
byts(count) = Convert.ToInt32(i)
count += 1
Next i
Return UTF8ByteArrayToString(byts)
End Function
Function UTF8ByteArrayToString(ByVal theChars As Byte()) As String
Dim aEncoding As System.Text.UTF8Encoding = New System.Text.UTF8Encoding()
Dim aConstructedString As String = aEncoding.GetString(theChars)
Return aConstructedString
End Function
Works perfect for me.