Excel VBA – 在sqlstring中使用撇号

我正在使用Excel将数据input到Access数据库中,并且我的一些数据string中包含一个用于测量的撇号。

这是我的SQLinputstring

stSQL = "INSERT INTO Products (ProductName, ProductDescription, ProductUnit, SupplierID) " & _ "Values ('" & cboxItemNum & "', '" & txtDescription & "', '" & txtUnit & "', " & linkPID & ")" cn.Execute (stSQL) 

我的string如下:

Aliplast 4E白色。 30“X 80'X 1/4”软。

在这个string中“80后导致错误,我不知道如何解决这个问题。 我不能告诉用户不要input撇号。 我怎样才能解决这个问题?

谢谢

您可以通过使用参数(推荐)或使用replace来更正此问题。

 & Replace(txtDescription,"'","''") & 

参数

 Dim cmd As New ADODB.command cn.Open ServerConnect cmd.ActiveConnection = cn stSQL = "INSERT INTO Products (ProductName, " _ & "ProductDescription, ProductUnit, SupplierID) " _ & "Values (param1,param2,param3,param4)" cmd.CommandText = stSQL cmd.CommandType = adCmdText With cmd .Parameters.Append .CreateParameter( _ "param1", adInteger, adParamInput, , cboxItemNum) .Parameters.Append .CreateParameter( _ "param2", adVarChar, adParamInput, 50, txtDescription ) .Parameters.Append .CreateParameter( _ "param3", adInteger, adParamInput, , txtUnit ) .Parameters.Append .CreateParameter( _ "param4", adInteger, adParamInput, , linkPID ) End with cmd.Execute recs 

请注意,尽pipe我将这些参数的参数param1命名为param4,这是为了我的方便,所有重要的是顺序,它必须与参数的使用顺序相匹配。

用包含在单引号中的值replace撇号(例如'O'Brien'中的O'Brien)如下:O'&''“&'Brien

使用下面的代码片段:replace(rs![field1],“'”,“'”&“&”&“”“”&“'”&“”“”&“&'”)&“'”) 。 注意我在单引号和双引号之间添加了一个空格,以便更容易区分它们。 在你使用的实际代码中,你不应该有这些空格。

例如

代替

Docmd.RunSQL(“INSERT INTO Tablename(DestinationField)SELECT'”&rs![field1]&“'”)

使用

Docmd.RunSQL(“INSERT INTO Tablename(DestinationField)SELECT'”&Replace(rs![field1],“'”,“'”&“&”&“”“”&“'”&“”“”& &'“)&”'“)

这为我工作,并允许我使用VBA插入包含撇号(单引号)到一个表中使用SQL插入语句