I need to separate a string with Visual Basic.
The downside is that i have more then one separator.
One is "+" and the other one is "-".
I need the code to check for the string if "+" is the one in the string then use "+"
if "-" is in the string then use "-" as separator.
Can I do this?
For example: Split( "TEXT" , "+" OR "-" ,2)
easiest way is to replace out the second character and then split by only one:
Dim txt As String, updTxt As String
Dim splitTxt() As String
updTxt = Replace(txt, "-", "+")
splitTxt = Split(updTxt, "+")
or more complex. The below returns a collection of the parts after being split. Allows you to cusomize the return data a bit more if you require:
Dim txt As String, outerTxt As Variant, innerTxt As Variant
Dim splitOuterTxt() As String
Dim allData As New Collection
txt = "test + test - testing + ewfwefwef - fwefwefwf"
splitOuterTxt = Split(txt, "+")
For Each outerTxt In splitOuterTxt
For Each innerTxt In Split(outerTxt, "-")
allData.Add innerTxt
Next innerTxt
Next outerTxt
What you describe seems pretty straightforward. Just check if the text contains a + to decide which separator you should use.
Try this code:
dim separator as String
separator = Iif(InStr(txt, "+") <> 0, "+", "-")
splitResult = Split(txt, separator, 2)
The code assumes that the text you want to split is in the txt variable.
Please note that I don't have VBA here and wasn't able to actually run the code. If you get any error, let me know.
Related
I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!
I am try to get value in the middle of a string
My string is
"arely browning,68097,19
I know I can use a substring and pick a specific place but I want it to work for any line that is format like this
If the format of the string remains the same, then this will do it:
Dim MyString As String = "arely browning,68097,19"
Dim StringPart As String = Mid(MyString, InStr(MyString, " "), InStr(MyString, ",") - InStr(MyString, " "))
I'm rooky for VBA. I have some problem about reversing my data on VBA-Excel. My data is "3>8 , 6>15 , 26>41 (each data on difference cells)" that i could reverse "3>8" to "8>3" follow my requirement by using function reverse. But i couldn't reverse "6>15" and "26>41" to "15>6" and "41>26". It will be "51>6" and "14>62" that failure, I want to be "15>6" and "41>26".
Reverse = StrReverse(Trim(str))
Help me for solve my issue please and thank for comment.
You first need to find the position of the ">" in the cell. you do this by taking the contents of the cell and treating it as a String and finding the ">"
This is done in the line beginning arrowPosition. This is the integer value of the position of the ">" in you original string
Next use Left to extract the text up to the ">" and Right to extract the text after the ">"
Then build a new String of rightstr & ">" & leftStr.
Note I input my data from Sheet1 B5 but you can just use any source as long as it is a String in the correct format.
Sub Test()
Dim myString As String
myString = Sheets("Sheet1").Range("B5")
Debug.Print myString
Debug.Print reverseString(myString)
End Sub
Function reverseString(inputString As String) As String
Dim leftStr As String
Dim rightStr As String
Dim arrowPosition As Integer
arrowPosition = InStr(1, inputString, ">")
leftStr = Left(inputString, arrowPosition - 1)
rightStr = Right(inputString, Len(inputString) - arrowPosition)
reverseString = rightStr & ">" & leftStr
End Function
just because you look for a VBA, you can add this function into your code:
Function rev(t As String) As String
s = Split(t, ">", 2)
rev = s(1) & ">" & s(0)
End Function
of course only if you have to reverse 2 number, otherwise you'll loop the "s", but the function would lose its usefulness
Issue, where the character I am removing does not exist I get a blank string
Aim: To look for three characters in order and only get the characters to the left of the character I am looking for. However if the character does not exist then to do nothing.
Code:
Dim vleftString As String = File.Name
vleftString = Left(vleftString, InStr(vleftString, "-"))
vleftString = Left(vleftString, InStr(vleftString, "_"))
vleftString = Left(vleftString, InStr(vleftString, " "))
As a 'fix' I have done
Dim vleftString As String = File.Name
vleftString = Replace(vleftString, "-", " ")
vleftString = Replace(vleftString, "_", " ")
vleftString = Left(vleftString, InStr(vleftString, " "))
vleftString = Trim(vleftString)
Based on Left of a character in a string in vb.net
If File.Name is say 1_2.pdf it passes "-" and then works on line removing anything before "" (though not "" though I want it to)
When it hits the line for looking for anything left of space it then makes vleftString blank.
Since i'm not familiar (and avoid) the old VB functions here a .NET approach. I assume you want to remove the parts behind the separators "-", "_" and " ", then you can use this loop:
Dim fileName = "1_2.pdf".Trim() ' Trim used to show you the method, here nonsense
Dim name = Path.GetFileNameWithoutExtension(fileName).Trim()
For Each separator In {"-", "_", " "}
Dim index = name.IndexOf(separator)
If index >= 0 Then
name = name.Substring(0, index)
End If
Next
fileName = String.Format("{0}{1}", name, Path.GetExtension(fileName))
Result: "1.pdf"
I am trying to clean up a string from a text field that will be part of sql query.
I have created a function:
Private Function cleanStringToProperCase(dirtyString As String) As String
Dim cleanedString As String = dirtyString
'removes all but non alphanumeric characters except #, - and .'
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
'trims unecessary spaces off left and right'
cleanedString = Trim(cleanedString)
'replaces double spaces with single spaces'
cleanedString = Regex.Replace(cleanedString, " ", " ")
'converts text to upper case for first letter in each word'
cleanedString = StrConv(cleanedString, VbStrConv.ProperCase)
'return the nicely cleaned string'
Return cleanedString
End Function
But when I try to clean any text with two words, it strips ALL white space out. "daz's bike" becomes "Dazsbike". I am assuming I need to modify the following line:
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
so that it also lets single white space characters remain. Advice on how to do so is greatly received as I cannot find it on any online tutorials or on the MSDN site (http://msdn.microsoft.com/en-us/library/844skk0h(v=vs.110).aspx)
Use "[^\w\.,#\-\' ]" instead of your pattern string.
Also, I would use
Regex.Replace(cleanedString, " +", " ")
instead of
Regex.Replace(cleanedString, " ", " ")
Or, if you are not a big fan of regex...
Private Function cleanStringToProperCase(dirtyString As String) As String
'specify valid characters
Dim validChars As String = " #-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
'removes all but validChars'
Dim cleanedString As String = dirtyString.Where(Function(c) validChars.Contains(c)).ToArray
Dim myTI As Globalization.TextInfo = New Globalization.CultureInfo(Globalization.CultureInfo.CurrentCulture.Name).TextInfo
'return the nicely cleaned string'
Return myTI.ToTitleCase(cleanedString.Trim)
End Function