Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I need some assistance in accommodating an apostrophe in an SQL statement using VBA in MS Access. Please help.

<br />strSQLHyperion = "SELECT [COUNTRY], [TYPE], [BUSINESS_UNIT], " & _<br /> "[ALT_GROUPING], [PERSONNEL_AREA], [L_R_G], [REGION], [JOB_FUNCTION], " & _<br /> "[PRIMARY_KEY] FROM [TBLHYPERION] " & _<br /> "WHERE [COUNTRY]='" & UCase(rstInputFile![COUNTRY]) & "' " & _<br /> "AND [TYPE]='" & UCase(rstInputFile![Type]) & "' " & _<br /> "AND [BUSINESS_UNIT]='" & UCase(rstInputFile![BUSINESS_UNIT]) & "' " & _<br /> "AND [ALT_GROUPING]='" & UCase(rstInputFile![ALT_GROUPING]) & "' " & _<br /> "AND [PERSONNEL_AREA]='" & UCase(rstInputFile![PERSONNEL_AREA]) & "' " & _<br /> "AND [L_R_G]='" & UCase(rstInputFile![L_R_G]) & "' " & _<br /> "AND [REGION]='" & UCase(rstInputFile![REGION]) & "' " & _<br /> "AND [JOB_FUNCTION]='" & UCase(rstInputFile![JOB_FUNCTION]) & "'"<br />

What do I need to do to prevent it from hanging up on the apostrophe? The apostrophe needs to be accepted in:

<br />"AND [JOB_FUNCTION]='" & UCase(rstInputFile![JOB_FUNCTION]) & "'" <br />

[confused][confused][confused]

modified on Wednesday, December 3, 2008 11:31 AM
Posted

You need to replace the apostrophy with 2 apostrophies. Best way is probably through a function (although I'm not sure of the exact syntax for VBA) - something like :

Public Function MakeSqlSafe(strData) as string
Return strData.Replace("'", "''")
end function

and then pass each one of your inputs through the function, e.g.

'" & MakeSqlSafe(UCase(rstInputFile![REGION])) & "'

Hope this helps.
 
Share this answer
 
Although replacing single apostrophe with double apostrophes will correct your problem, I think you should use parameters instead. Concatenating literal strings leaves you open to sql injections. Also using parameters gives a performance advantage.

 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900