Is it possible to replace " (double quotes) with a white space in a string? - sql

At some point of execusion of my project, the input to the database is in the format:
Buy Requirement of "xxxxxx & xxxxxx" through mycompany.com
It results in an incorrect SQL syntax error. I need to replace " with white space. I searched in google but no helpful suggestions were there.
How to replace " with whitespace?
Dim str As String
str="Buy Requirement of "Telemarketing & ERP Software" through IndiaMART.com"
' TODO: perform replace
' result
str = "Buy Requirement of Telemarketing & ERP Software through IndiaMART.com"

I finally understand what you are asking now...
Here, this is what you want to be using: teststring.Replace(""""c, "")
If you really want to use Linq and extension methods, then use this: New String(teststring.Where(Function(c) Char.IsLetterOrDigit(c) OrElse Char.IsWhiteSpace(c)).ToArray()).
But that's just making things complicated for no reason.

Related

Escaping special characters in Microsoft Access 2016

I am working on a project for the company I work for, designing a database to keep track of and create project numbers. I have it up and running, but my supervisor has asked that I include user-input sanitizing to escape special characters that could cause a problem for the existing code and SQL. I have a few different user-input forms, which are just bound text boxes which get entered into my table when the form is closed. I also have one Input Box, which asks for the project number which an employee would like to update the info for.
From my understanding, a local Access database on our company server is not going to be very prone to SQL injection, and MS Access has a way of handling injection which I do not really understand. However, I am looking for a list of characters which could potentially cause problems, where they could potentially cause problems, and the best way to deal with them.
I have tried inputting a few different special characters which I know to be problematic into the text boxes on the forms, but Access just parses them straight into the record, with no errors. I DO have one function written in which replaces single apostrophes with two apostrophes, and this is used on the InputBox.
Here is the code behind the InputBox:
Private Sub btnOpenUpdate_Click()
Dim strInput$, safeInput$
strInput = InputBox("Enter the EP-Number for the project that you would like to update:", "Update Project")
safeInput = safeEntry(strInput) 'change all single apostrophes to double apostrophes '
If Len(safeInput & vbNullString) > 0 Then
If DCount("EPNumber", "tblProjects", "EPNumber = '" & safeInput & "'") > 0 Then
DoCmd.OpenForm "frmUpdateProject", , , "EPNumber = '" & safeInput & "'"
Else
MsgBox "Please enter a valid EP-Number.", vbInformation, "Error: Invalid EP-Number entered"
End If
Else
MsgBox "The field was left blank. Please enter a valid EP-number.", vbInformation, "Error: Empty field"
End If
End Sub
And here is the code behind the safeEntry function:
Public Function safeEntry(strEntry)
safeEntry = Replace(Nz(strEntry), "'", "''")
End Function
Apologies for the somewhat lengthy summary of my situation, but any help and input would be very appreciated, as I am fairly new to the world of MS Access and SQL, and I am trying my best to learn how to protect the database.

Db Search - Multiple conditions

I am trying to export Documents from a Lotus DB. I have used the Db.search functionality and arrived at below code. However, I want to include 2 conditions/functions - #Contains & #Created together. I am getting Formula error. Any help is much appreciated.
Set GlobalCollection = db.Search("#Created > [01/01/2019]" & " " & "#Contains(" & "App1" & ";" & """Approved""" & ")", Nothing, 0)
The escape symbol for LotusScript is a backslash, \. LotusScript allows you to use more than just double quotes to wrap Strings. You can use curly braces ({...}) or pipes (|...|). This may make it more readable and easier to trubleshoot. There's also no need to have separate strings for each individual piece, which will again minimise risk and help readability. There may have been a mistake with each of those, I'm pretty sure you're missing an ampersand. It's much easier to troubleshoot with fewer strings.
So this should work:
Set GlobalCollection = db.Search({#Created > [01/01/2019] & #Contains(App1;"Approved")}, Nothing, 0)

How can I use special chars in VBA of Microsoft Word?

I've created a set of macro files in Microsoft Word's VBA as a sort of a CAT tool (CAT = https://en.wikipedia.org/wiki/Computer-assisted_translation). The problem is that there are cases where I display the text needed to be translated and the user needs to input text in his own language. That might include some special chars, like "ăîâșț/ĂÎÂȘȚ", or even quotes or brackets. Is there any way to use those in some InputBox function? Or, at least, some way to let the user input the text he needs in some TextBox or something?... Or how should I approach this?... Maybe UTF-8 support would be what I need? Or?... Any help would be appreciated!...
I've tried Microsoft Word's vba function InputBox. I'm also thinking if, maybe, I would be able to create my own InputBox, with my conditions on it, I might be able to have one that accepts those chars too, or all the chars into some string variable... Here is something someone on StackOverflow says:
Is it possible to create an 'input box' in VBA that can take a text selection with multiple lines as an input? (I'm referring to gizlmo's answer...)
Here are 3 lines of code that contain that (although it's more of a how to question, not a debugging question, so those are not really needed...)
MsgBox ("Ziua " & Str(ziua) & " - " & titlurien(ziua))
titluales = InputBox("Titlul original: " & titlurien(ziua), "Ziua: " & Str(ziua) & ", Rapsodia Realitatilor " & monthname(lunanecesara) & Str(annecesar))
titluriro(ziua) = titluales
I expect the output to be exactly what he typed, whether it's quotes, brackets or special characters (like "ăîâșț"/"ĂÎÂȘȚ")...
A VBA InputBox will take any character typed or pasted into it. The characters available to type depends on the Language version of Windows and Office that the end user has installed.
Below is a test I just made with your example character string "ăîâșț/ĂÎÂȘȚ"
SpecialCharInput()
Dim str As String
str = InputBox("Enter you text", "Special Test Input Box")
Debug.Print str
End Sub
On my English language system, the only trouble it had was with the upper and lower case "ȘȚ" Turkish characters. By trouble I mean it turned those characters into question marks "??" in the result string. I'm sure though, if my system supported the Turkish language that those characters would be recognized and outputted properly.

How to build proper Access SQL LIKE operator expression?

I'm attempting to have a user search through a table in Microsoft Access 2010, but the SQL command isn't working. The command that loads and refreshes the table is this:
SELECT Equipment.equipmentID, Equipment.equipmentName, Equipment.model,
Equipment.make, Equipment.equipmentLocation FROM Equipment ORDER BY Equipment.equipmentName;
This works, but when I try to use a variable (or any normal criteria):
searchItem = Me.searchBox.Value
Me.List64.RowSource = "SELECT Equipment.equipmentID, Equipment.equipmentName,
Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment
WHERE Equipment.equipmentName LIKE '%searchItem%' ORDER BY Equipment.equipmentName;"
I've also tried something like "%10%" instead of the searchItem variable, but the command has the table come up blank with no errors. I suspect the problem is with the Equipment.eqiupmentName as the column name, but I can't quite figure out what's wrong here.
Here's a quick look at what the table looks like:
Try this:
Me.List64.RowSource = & _
"SELECT Equipment.equipmentID, Equipment.equipmentName," & _
" Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment" & _
" WHERE Equipment.equipmentName LIKE '*" & searchItem & "*'" & _
" ORDER BY Equipment.equipmentName;"
User rjt011000 has a valid solution, but I recommend using & for string concatenation in VBA (and Access). For an explanation of + and & see this thread.
Access will not recognize or substitute VBA variables inside an SQL statement. Furthermore, the LIKE operator is fed an SQL string value in this case (inside single quotes... which are inside the double quotes), so even if a VBA variable could be referenced directly inside SQL, Access does not interpret any such thing inside a string value.
Regarding the Access SQL LIKE operator, the multi-character matching pattern is * rather than %. Access also recognizes the operator ALIKE which does indeed honor the ANSI pattern %. See LIKE operator docs and this thread regarding ALIKE.
To be more thorough, the string delimiters and LIKE pattern-matching character should be escaped if you don't want the user inadvertently injecting invalid characters that cause errors in the SQL. Following is an example of escaping a couple of them. There are more elegant ways to handle this for all special characters, but the code and technique are beyond the scope of this answer.
...'" & Replace(Replace(searchItem, "*", "[*]"), "'", "''") & "'...
For the record, although Access SQL will not substitute a VBA variable, it will recognize and call a public VBA function. Normally such a public function must be defined in a normal module, but in context of a form's Record Source query, a form-module method can sometimes be called.
One last technique... It is possible to reference a form control's value directly in SQL. This can be very convenient and reduce extra code, but there are a couple caveats:
The form must of course be open, otherwise Access will interpret the reference as an unknown parameter and display a prompt. This will of course not be a problem if the SQL is always in context of the same form.
Access will sometimes automatically refresh the query when such a referenced control is changed, but it is not always guaranteed. The "timing" of automatic refreshes might not be immediately intuitive. You can call the Refresh method on the control or subform from various form events to force the query to refresh after the value is changed.
Notice that in the following example, the string concatenation is inside the VBA string, so that the concatenation actually happens in context of SQL and not beforehand like in the first code snippet. There is no problem with this, just something to consider since this entire answer revolves around proper string interpretation and concatenation.
But really, the same concern exists for un-escaped pattern-matching characters in the user text. Rather than making the SQL text long and ugly with calls to Replace(), instead create a custom function (e.g. EscapePattern()) that does this for any text and then wrap the control reference with that function. The example does this, although I don't include the code for the special function. Such a function could also be used in the first VBA code snippet to simplify building the SQL text.
Me.List64.RowSource = & _
"SELECT Equipment.equipmentID, Equipment.equipmentName," & _
" Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment" & _
" WHERE Equipment.equipmentName LIKE ('*' & EscapePattern(Forms![Form Name]![Control Name]) & '*')" & _
" ORDER BY Equipment.equipmentName;"
There is always more! Did you see the VBA line continuation in my example? It makes the SQL text much easier to view within VBA editor.
I suspect you are not setting your searchItem variable correctly in the SQL string. I am not too familiar with access string concatenation but try separate the searchItem out of the SQL string and then checking if your RowSource has the value you suspect.
Me.List64.RowSource = "SELECT Equipment.equipmentID, Equipment.equipmentName,
Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment
WHERE Equipment.equipmentName LIKE '%" + searchItem + "%' ORDER BY Equipment.equipmentName;"

Creating Multiple Links in an Access Textbox

I have a form in Access 2016 with a textbox in which I need to have multiple, semi-colon delimited hyperlinks (which will be dynamically created). What I've decided to do is create a "hyperlink construction string" in VBA, then assign them to the value of the textbox. So, something like:
Me.Field.Value = {link: www.google.com : "Google"} & "; " & {link: www.yahoo.com : "Yahoo"}
...would result in this being in the text box:
Google; Yahoo
My problem is, I can't seem to figure out the syntax to create an individual link in the textbox without making the entire textbox a single hyperlink, which isn't gonna work.
I was working with a few solutions that I've found. I read that this would create the link in the way I need, but it just comes through as literal text with the pound signs:
"Google # www.google.com # Some Argument"
I also tried setting the textbox to rich text, then setting the value to include rich text code for a hyperlink... but that's not working:
"{\field{\*\fldinst HYPERLINK ""http://www.google.com/""}{\fldrslt http://www.google.com}}"
I also thought about designing a Query that will return the hyperlinks. But, I kind of wanted to make it a VBA thing, because I'll have more flexibility in how I create the value. Does anyone have any ideas?
Note: I understand that multiple values should be in a 1:M relational database. They are. But, the requirements of the task are to get all the M values for a 1 entity, then list them out in semi-colon, delimited fashion, which all serve as links to a Details table for the M entity.
Regular textboxes (text only) don't support this.
It is possible with Rich text textboxes. In contrast to the name, they actually use a subset of HTML, not RTF.
With ideas from here I got this working:
Private Sub cmdInsertHyperlinks_Click()
Dim url1 As String, url2 As String
url1 = "D:\tmp\test.jpg"
url2 = "D:\tmp\test space.txt"
Me.rText.Value = "<div>" & _
"file://" & url1 & "" & _
" other text between hyperlinks " & _
"file://" & url2 & "" & _
"</div>"
End Sub
Note: the linked thread says you must URL-encode the links (space to %20 etc), but at least for my simple test, that wasn't necessary.
Note 2: You can't have a different display text and link url, at least I didn't get that to work.