Connecting Tech Pros Worldwide Forums | Help | Site Map

Apostrophe causes error in SQL string: Solution

sashi's Avatar
Expert
 
Join Date: Jun 2006
Location: Seremban, Malaysia
Posts: 1,630
#1   Dec 4 '06
Apostrophe

Have you ever tried to send a string variable to MS Access that had apostrophes embedded within an SQL Statement? If YES you will get a run time ERROR. Here is your solution, a function that formats the variable before sending it to the database.

Expand|Select|Wrap|Line Numbers
  1. Public Function Apostrophe(sFieldString As String) As String
  2.   If InStr(sFieldString, "'") Then
  3.     Dim iLen As Integer
  4.     Dim ii As Integer
  5.     Dim apostr As Integer
  6.     iLen = Len(sFieldString)
  7.     ii = 1
  8.  
  9.       Do While ii <= iLen
  10.         If Mid(sFieldString, ii, 1) = "'" Then
  11.           apostr = ii
  12.           sFieldString = Left(sFieldString, apostr) & "'" & _
  13.           Right(sFieldString, iLen - apostr)
  14.           iLen = Len(sFieldString)
  15.           ii = ii + 1
  16.         End If
  17.       ii = ii + 1
  18.       Loop
  19.   End If
  20.  
  21.   Apostrophe = sFieldString
  22. End Function
  23.  



Closed Thread