I'm running an Insert Into SQL query from VBA, and I recently came across the string 'Women's Health / Sexual Health', which contains the ' character, and thus the query failed because ' is a text delimiter. This is how I get the text for the query:
Function getSqlInsertIntoQuery(arrHeaders, arrValues, tableIndex As enumTables)
Dim dHeadersAndValues As New scripting.Dictionary
Dim TableName As String
TableName = getTableName(tableIndex)
getSqlInsertIntoQuery = "INSERT INTO " & TableName & " ( [" & _
Join(arrHeaders, "]," & vbNewLine & "[") & "])" & _
" VALUES( " & Chr(39) & Join(arrValues, Chr(39) & "," & Chr(39)) & Chr(39) & ") ;"
Debug.Print getSqlInsertIntoQuery
End Function
Can anyone tell me of a way to clean the text of special characters that I should escape? Or is there a list of characters that I can replace using regex?
Related
I have the following formula that I am inputting in a function.
dim minfee, feetier3, feetier4, feetier5, bpspread1, bpsread2, bpspread3 as double
call insformulaincell("=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))")
'all the function does is paste the formula into a cell
'How would I format the formula so that it can be stored as a single string?
'Ex:
dim sFormula as string
sformula = ""=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))""
call insformulaincell(sFormula)
The main issue is that the variables such as minfee would not reference its actual values but instead have the actual string variable name appear.
Ex: "... If(K2 <" & minfee & "," ... )
as opposed to
"... If(K2 < 1) ..." ' assuming that minfee = 1
In VBA " serves as a delimiter for string literals, like this:
Dim foo As String
foo = "some string"
If your string literal needs to contain " double quotes, you need to escape them, by doubling them up between the string delimiters:
foo = """some string"""
Printing the above would yield "some string", including the double quotes.
So you do need to remove the leading & trailing double quotes.
sformula = "=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))"
Breaking this down, it's a concatenation of the following literals:
"=IF(K2 = 100, ""#NA"", IF(K2 <" (note, "#NA" is a bad idea IMO. Use the NA() function to yield an actual worksheet error instead of a string value that looks like one)
","
",IF(K2<"
",K2+ "
",IF(K2<"
",K2+ "
",K2+ "
"))))"
Which looks right to me.
Arguably, such concatenation is annoyingly confusing. A custom StringFormat function can help mitigate this, by abstracting away the concatenations:
sFormula = StringFormat("=IF(K2=100, ""#NA"", IF(K2<{0},{1},IF(K2<{2},K2+{3},IF(K2<{4},K2+{5},K2+{6}", _
minfee, feetier3, feetier4, bpspread1, feetier5, bpspread2, bpspread3)
I am trying to create a basic data entry form, however, it is turning into more trouble than I anticipated.. I have the form created, now I am just trying to INSERT the data into the DB (TEST). I am receiving an "Object Required" error. Any suggestions? All of the txt boxes are verified to be correct. This is all being done through Access VBA
Private Sub Command28_Click()
Dim sSQL As String
Set sSQL = "INSERT INTO TEST (Carrier_Ent_ID, Row_Insert_TS, Row_Update_TS,
Row_Insert_User_ID, Row_Update_User_ID, Carrier_Ent_Name, Active)
VALUES (" & Me.txtENTID & "," & Me.txtDate & "," & Me.txtDate & "," &
Me.cmboUserID & "," & Me.cmboUserID & "," & Me.txtENTNAME & ","
& Me.Txtactive & "); "
DoCmd.RunSQL.sSQL
End Sub
From what I can see there's a couple of mistakes in the code.
You only use SET when setting a reference to an object - sSQL is a text string.
DoCmd.RunSQL shouldn't have a full-stop after RunSQL- just the text string.
If Me.txtENTNAME is a text string it should have an apostrophe before and after it.
Private Sub Command28_Click()
Dim sSQL As String
'No Set & ' before and after Me.txtENTNAME (assuming it's text).
sSQL = "INSERT INTO TEST (Carrier_Ent_ID, Row_Insert_TS, Row_Update_TS, " & _
"Row_Insert_User_ID, Row_Update_User_ID, Carrier_Ent_Name, Active) " & _
"VALUES (" & Me.txtENTID & "," & Me.txtDate & "," & Me.txtDate & "," & _
Me.cmboUserID & "," & Me.cmboUserID & ",'" & Me.txtENTNAME & "'," & Me.txtActive & "); "
'No full stop after RunSQL.
DoCmd.RunSQL sSQL
End Sub
why the following msaccess vba statement fails when add the where statement?
I want to check if the field has value
Set rsMySet = CurrentDb.OpenRecordset("PivotTblInvDepts")
'Start the count at the position number of the first column-oriented field
'Remember that Recordsets start at 0
For i = 3 To rsMySet.Fields.Count - 1
'*********************************************************************************************************************
'Use the recordset field.name property to build out the SQL string for the current field
strSQL = "INSERT INTO TabularDepts ([Depts], [Code], [Description], [Qty])" & _
"SELECT" & "'" & rsMySet.Fields(i).Name & "'" & " AS Dept," & _
"[PivotTblInvDepts].[Code],[PivotTblInvDepts].[Description]," & _
"[" & rsMySet.Fields(i).Name & "]" & _
"FROM PivotTblInvDepts;" & _
"WHERE" & " (rsMySet.Fields(i).Name)>0"
Try removing the ; in FROM PivotTblInvDepts;.
Also you need space at the end of the previous line. "[" & rsMySet.Fields(i).Name & "]" & _ should be "[" & rsMySet.Fields(i).Name & "] " & _. Likewise, make sure to add a space so that you do no result in FROM PivotTblInvDeptsWHERE
Your current SQL reads something like this
INSERT INTO TabularDepts ([Depts], [Code], [Description], [Qty])
SELECT '<data>' As Dept,
[PivotTblInvDepts].[Code],[PivotTblInvDepts].[Description],
[<data>]
FROM PivotTblInvDepts;
WHERE <condition>
After removing the ;, the insert will be cleaner.
I need some help with my query I am trying to insert to a table see above code:
CurrentDb.Execute ("INSERT INTO tblWarehouseItem ( whiwrhID, whiItemName, whivatName," whiVatRate, whiimtID, whiQty, whiPrice, whisupID, whiDateIn, whiExpiryDate,whiwhiID ) " & _
" Values (" & rs!WID & "," & Chr(34) & rs!N & Chr(34) & "," & Chr(34) & rs!VN & Chr(34) & "," & rs!VR & "," & rs!IID & "," & intQtyForm & "," & rs!PR & "," & rs!SID & "," & CDate(rs!DIN) & "," & CDate(rs!EXD) & "," & rs!ID & ")")
In my table the CDate(rs!EXD) and CDate(rs!DIN) are stored as time.
When I compile my query in the immediate window I get Dates.
INSERT INTO tblWarehouseItem ( whiwrhID, whiItemName, whivatName, whiVatRate, whiimtID, whiQty, whiPrice, whisupID, whiDateIn, whiExpiryDate,whiwhiID ) Values (2,"ITEM10","A",19,14,4,20,10,21/07/14,26/05/14,60)
How can I make my query to insert the date in the table?
thanks in advance
If you run that 21/07/14 is passed to Access and interpreted as an integer resulting from 12 divide by 7 divide by 14 which when converted to a date is just a time.
Delimit dates with #:
.. ",#" & CDate(rs!DIN) & "#," ..
is there any posibility to select a string in an odbc query?
i want select the sum of many excel sheets and also need the name of the excel sheet in the resulting pivottable, so i tried something like this:
strSQL = "SELECT Sum(`table" & i & "`.`Stunden`), " & GetFilenameFromPath(arrFiles) & " FROM [" & strSheet & "$] `table" & i & "` WHERE `table" & i & "`.`Stunden` IS NOT NULL"
but the select statement " & GetFilenameFromPath(arrFiles) & "
does not work right... a select of 1 works instead!
e.g:
strSQL = "SELECT Sum(`table" & i & "`.`Stunden`), 1 FROM [...]
do i have to escape the string in any form?
thanks
Well, GetFilenameFromPath will return you a string, so you need to encase this in quotes:
strSQL = "SELECT Sum(`table" & i & "`.`Stunden`), '" & GetFilenameFromPath(arrFiles) & "' FROM...
Although, I'd encourage you to be more explicit in your question. Details of the expected output of GetFilenameFromPath for you, and a specific error message would be very helpful.