String surronded by single quotation mark - vb.net

so I have this check combo box data source from SQL Server
Let's say I have these string value from the combo box
ABC, DEF, GHI
What I wanted next is get those string
and make them become like this
'ABC', 'DEF', 'GHI'
I've tried combining them with "'" & comboBox.Text & "'"
but it looks like this
'ABC, DEF, GHI'

You're starting with a delimited string and you want to process each substring separately, so that means splitting, processing and joining the string. There are a number of variations on a theme that will do that. Here are a couple of examples:
Dim substrings = comboBox.Text.Split(","c)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i).Trim() & "'"
Next
Dim result = String.Join(", ", substrings)
Dim result = String.Join(", ",
comboBox.Text.
Split(","c).
Select(Function(s) $"'{s.Trim()}'"))
Note that, if you're confident that there will always be a comma and one space between substrings then you can incorporate the space into the Split and do away with the Trim:
Dim substrings = comboBox.Text.Split({", "}, StringSplitOptions.None)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i) & "'"
Next

Well, you can do it LINQ style like:
Dim res as string = String.Join(“, “, String.Split(“,”c, original).Select(Function(f) $”’{f.Trim}’”))
The process is to split the original into its component parts, remove any white space, add surrounding quotes and combine back into a single string with “, “ as a separator.

Related

Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', "

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks
Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

String builder SELECT query when a variable has an apostrophe

A colleague of mine has created a program that reads a text file and assigns various values from it to variables that are used in SQL statements.
One of these variables, gsAccounts is a string variable.
Using a string builder, a SELECT statement is being built up with sql.append. At the end of the string, there is the following line:
sql.Append(" WHERE L.Account_Code IN(" & gsAccounts & ")"
The problem that I'm having is that sometimes, not always, gsAccounts (a list of account codes) may contain an account code with an apostrophe, so the query becomes
"WHERE L.Account_Code IN('test'123')"
when the account code is test'123
I have tried using double quotes to get around it in a "WHERE L.Account_Code IN("""" & gsAccounts & """")" way (using 4 and 6 " next to each other, but neither worked)
How can I get around this? The account_Code is the Primary Key in the table, so I can't just remove it as there are years worth of transactions and data connected to it.
I posted the following example here 10 years ago, almost to the day. (Oops! thought it was Jun 5 but it was Jan 5. 10.5 years then.)
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand
Dim query As New StringBuilder("SELECT * FROM MyTable")
Select Case Me.ListBox1.SelectedItems.Count
Case 1
'Only one item is selected so we only need one parameter.
query.Append(" WHERE MyColumn = #MyColumn")
command.Parameters.AddWithValue("#MyColumn", Me.ListBox1.SelectedItem)
Case Is > 1
'Multiple items are selected so include a parameter for each.
query.Append(" WHERE MyColumn IN (")
Dim paramName As String
For index As Integer = 0 To Me.ListBox1.SelectedItems.Count - 1 Step 1
'Name all parameters for the column with a numeric suffix.
paramName = "#MyColumn" & index
'Add a comma before all but the first value.
If index > 0 Then
query.Append(", ")
End If
'Append the placeholder to the SQL and add the parameter to the command
query.Append(paramName)
command.Parameters.AddWithValue(paramName, Me.ListBox1.SelectedItems(index))
Next index
query.Append(")")
End Select
command.CommandText = query.ToString()
command.Connection = connection
Single quotes can be "escaped" by making them double single quotes. E.g. ' becomes ''.
However this approach is generally not recommended due to the high risk of SQL injection - a very dangerous and prevalent issues. See: https://www.owasp.org/index.php/SQL_Injection
To avoid this most libraries will include some type of escaping mechanism including the use of things like prepared statements in the Java world. In the .net world this may be of use: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare(v=vs.110).aspx
If you only have one with a field, this is the easiest solution
Private Function gsAccountsConvert(ByVal gsAccounts As String)
Dim gsAccountsString As String = ""
Dim StringTemp
StringTemp = gsAccounts.Split(",")
Dim i As Integer
For i = 0 To UBound(StringTemp)
StringTemp(i) = StringTemp(i).ToString.Trim
If StringTemp(i) <> "" Then
If StringTemp(i).ToString.Substring(0, 1) = "'" Then
StringTemp(i) = """" & StringTemp(i).ToString.Substring(1, Len(StringTemp(i).ToString) - 2) & """"
End If
End If
If i <> UBound(StringTemp) Then
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ","
Else
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ""
End If
Next
gsAccountsString = gsAccountsString.Replace("""", "'")
Return gsAccountsString
End Function

Handle comma in csv file: VBA

I am using following code to read csv file and finally the data is converted into array.
Function Sample(strPath) As String()
Dim MyData As String, strData() As String
Open strPath For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
Sample = Split(MyData, vbCrLf)
End Function
Following code convert each comma separated line into array.
SaleRows = Sample(filepath)
For Each SaleRow In SaleRows
SaleRowArray = Split(SaleRow, ",")
Next SaleRow
Everything works fine but when a cell contains comma, my above function fails. Is there any way to handle comma in a particular cell?
Sample csv
Please observe comma in second row.
When I get array from the comma record, I get below.
It's likely that the strings in your CSV file are escaped with quote marks. If you want to parse the CSV using your own code, then your code needs to be able to ignore commas which occur inside quotes.
A quick way to do this would be to use RegEx. You could try the following:
Private Function changeDelimiter(line as String) as String
Dim regEx As Object
Set regEx = CreateObject("VBScript.regexp")
regEx.IgnoreCase = True
regEx.Global = True
regex.Pattern = ",(?=([^" & Chr(34) & "]*" & Chr(34) & "[^" & Chr(34) & "]*" & Chr(34) & ")*(?![^" & Chr(34) & "]*" & Chr(34) & "))"
changeDelimiter = regex.Replace(line, "#|#")
End Function
Then change the Split() line in your code as follows:
SaleRowArray = Split(changeDelimiter(SaleRow), "#|#")
The function replaces all commas outside quote marks with #|# (which I assume won't ever come up in your input data). You then split the lines into data fields on #|# instead of comma.

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