我有一个excel vba函数从sql中提取数据,代码如下:
Function GetDCF(vari As String)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim strConn As String
Dim sql As String
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=xxxxx;INITIAL CATALOG=xxxxx;INTEGRATED SECURITY=sspi;"
cn.Open strConn
sql = "select * from table1 where COMPANY = '" & Range("A2").Value & "' "
rs.Open sql, cn, adOpenDynamic, adLockOptimistic
GetDCF = rs.Fields(vari) / 100
cn.Close
Set rs = Nothing
Set cn = Nothing
End Function
现在一切正常,除非我有一个像Mike的狗一样的公司,撇号阻止了sql查询运行良好。我想我会切换到参数化查询。但是我不确定在这种情况下怎么做?
感谢您的任何建议!
答案 0 :(得分:2)
正如我在评论中提到的,您可以使用Replace
在SQL查询中转义单引号:
sql = "select * from table1 where COMPANY = '" & Replace(Range("A2").Value, "'", "''") & "' "