Replace small u with single quote in vba - vba

I want to replace u' from the string using VBA. So, u'DROP_MOBILE': u'1234567890' and I need to change it as "DROP_MOBILE": "1234567890"
I tried with
strText = "u'DROP_MOBILE': u'1234567890'"
newstrTxt = Replace(strText, "u'", """")
it returns u"DROP_MOBILE": u"1234567890"
it only remove the single quote after u and u does not gets removed.

You can nest the replace, one to remove u and the other to replace the single quotes ' with double ".
Const strText As String = "u'DROP_MOBILE': u'1234567890'"
Debug.Print Replace(Replace(strText, "u", ""), "'", """")
'"DROP_MOBILE": "1234567890"

Related

How to skip splitting delimited string inside a string array in vba

I have a VBA macro where I need to get splitStr(1) = str2,str3; splitStr(2) = str4;....
string1 = "str1,""str2,str3"",str4,str5,str6"
splitStr = Split(string1,",")
Debug.Print splitStr(1)
"str2
Thanks
The Split(expression [,delimiter] [,limit] [,compare] ) function is searching through your string character by character looking for the delimiter or substring by substring depending on your delimiter. You have a few choices:
Use Split(string1,",") and get the resulting array in splitStr as follows:
splitStr(0) = str1
splitStr(1) = "str2
splitStr(2) = str3"
splitStr(3) = str4
splitStr(4) = str5
splitStr(5) = str6
Then use the following code to "fix" your result the way you want
splitStr(1) = Replace(splitStr(1), """", "") & Replace(splitStr(2), """", "")
'splitStr(1) now contains str2str3
'splitStr(2) still contains str3"
Split strings maintaining tokens within quotation marks
Try this approach using a temporary conversion to the â–ºByte type, which allows to loop faster through strings.
Method
Basically all commata within quotation marks are temporarily converted to another character (e.g. a semicolon), so that you can split as usual by substituting eventually semicolons back to normal commata.
See further explanations in the following code example:
Sub testByte()
Const COMMA& = 44, QUOT& = 34, SEMI& = 59 ' constants for comma, quot.mark, semicolon
Dim b() As Byte, i As Long, bQU As Boolean
Dim string1$, sTemp$
' [0] string to be splitted
string1 = "str1,""str2,str3"",str4,str5,str6"
' [1] temporary conversion of commatas in quotations to another character using the BYTE type
b = string1 ' Assign string to bytes
For i = 0 To UBound(b) Step 2 ' check each bytes representation of character
If b(i) = QUOT Then bQU = IIf(bQU, False, True) ' check quotation starts
If bQU Then If b(i) = COMMA Then b(i) = SEMI ' change commata in quotation to temporary semicolons
Next i
sTemp = b ' convert bytes to normal string type
' [2] split as usual
Dim splitStr As Variant
splitStr = Split(sTemp, ",")
' [3] check all results
For i = 0 To UBound(splitStr) ' list all splitted items and ...
Debug.Print i, Replace(splitStr(i), ";", ",") ' ... change semicolons back to normal commata
Next i
End Sub
'Results in immediate window
'---------------------------
'0 str1
'1 "str2,str3"
'2 str4
'3 str5
'4 str6
Note
Of course there is some intentional redundance in variables string1 and sTemp allowing additional testings :-)

How to replace a character within a string

I'm trying to convert WText into its ASCII code and put it into a TextBox; Numencrypt. But I don't want to convert the spaces into ASCII code.
How do I replace the spaces with null?
Current code:
Dim withSpace As String = Numencrypt.Text
For h = 1 To lenText
wASC = wASC & CStr(Asc(Mid$(WText, h, 1)))
Next h
Numencrypt.Text = wASC
Numencrypt2.Text = Numencrypt2.Replace(Numencrypt.Text, " ", "")
By the way, the TextBox Numencrypt2 is the WText without a space inside it.
Without knowing whether or not you want the null character or empty string I did the following in a console app so I don't have your variables. I also used a string builder to make the string concatenation more performant.
Dim withSpaces = "This has some spaces in it!"
withSpaces = withSpaces.Replace(" "c, ControlChars.NullChar)
Dim wASC As New StringBuilder
For h = 1 To withSpaces.Length
wASC.Append($"{AscW(Mid(withSpaces, h, 1))} ") ' Added a space so you can see the boundaries ascii code boundaries.
Next
Dim theResult = wASC.ToString()
Console.WriteLine(theResult)
You will find that if you use ControlChars.NewLine as I have, the place you had spaces will be represented by a zero. That position is completely ignored if you use Replace(" ", "")

Left split, getting blank return.

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"

Cleaning text strings in vb

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

Split( "TEXT" , "+" OR "-" ,2)

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.