vba从sql server记录集中获取值

时间:2014-10-16 15:00:57

标签: sql sql-server excel vba excel-vba

我检索值的代码如下:

Sub UploadData()
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=.\sql2000;INITIAL CATALOG=EquityDB;INTEGRATED    SECURITY=sspi;"

cn.Open strConn

sql = "select * from  EquityDB.dbo.table1 where field1 = '" & Replace(Range("d1").Value, "'", "''") & "'"

 rs.Open sql, cn, adOpenDynamic, adLockOptimistic
  GetData = rs.Fields(0).Value


 If Not GetData = "" Then

 cn.Execute sql001

 Else

 cn.Execute sql002

End If

sql001是插入,sql002是更新

当我运行宏时,我收到错误,说明当行打开记录时不允许操作

    rs.Open sql, cn, adOpenDynamic, adLockOptimistic

如果我改变

   If Not GetData = "" Then

   If Not GetData Is Null Then

我在行

时收到“需要对象”的错误
   If Not GetData Is Null Then

关于如何修复错误的任何建议都会很棒!

1 个答案:

答案 0 :(得分:3)

测试是否有任何内容返回到您的记录集中,而不是:

 GetData = rs.Fields(0).Value    

 If Not GetData = "" Then

使用:

If not(rs.eof and rs.bof) then

如果记录集不为空,则返回true。