Excel VBA ADO recordset issue with Null values - sql-server

I'm pretty new at VBA and having an issue with ADO.
Currently the code im using returns fields (Name, Suburb, State) from a SQL database into a ListBox.
The code works fine as long as there are there all fields have a value, if there is a Null value it returns the error
Could not set the List property. Type mismatch
I need to find a way so if the Suburb and/or State fields return a Null value that it still populates the Listbox.
Any info would be greatly appreciated, thanks in advance!
Database entries
Screenshot of error
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQLquery As String
Dim cnnstr As String
Dim SQLName As String
Dim i As Integer
SQLName = "Salon"
SQLquery = "SELECT [Name], [Suburb], [State] FROM Salon WHERE Name like '" & SQLName & "%'"
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=localhost; " & _
"Initial Catalog=MyDatabase;" & _
"User ID=sa;" & _
"Password=Password;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr
cnn.Execute SQLquery
rs.Open SQLquery, cnn, adOpenStatic
rs.MoveFirst
i = 0
With Me.lb_search
.Clear
Do
.AddItem
.List(i, 0) = rs!Name
.List(i, 1) = rs!Suburb
.List(i, 2) = rs!State
i = i + 1
rs.MoveNext
Loop Until rs.EOF
End With
btn_search_test_Exit:
On Error Resume Next
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing

Iif can return an alternate for Null Values.
For example:
.List(i, 0) = IIf(IsNull(a), "(not found)", rs!Name)
will return "(not found)" if the value is null.
More info here and here.

nz is annoyingly not-available in Excel
Oh yes it is :-)
Public Function NZ(v As Variant, Optional valueifnull As Variant = 0) As Variant
If IsNull(v) Then
NZ = valueifnull
Else
NZ = v
End If
End Function

Related

VBA SQL Server Query Connecting but not Returning Records

I have this VBA code that issues a SQL Server query after a successful connection but the query returns no records (e.g., -1)
Function invested_funds() As Integer
Dim c As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connectionstring As String
Dim sql As String
connectionstring = "Provider=SQLOLEDB;Data Source=DESKTOP-2TTG3GQ\SQLEXPRESS;" & _
"Initial Catalog=DB;" & _
"Integrated Security=SSPI;"
Set c = New ADODB.Connection
Set rs = New ADODB.Recordset
c.Open connectionstring
sql = "select [DB].[dbo].[db].[CSRoot] " & _
"from [DB].[dbo].[db] "
If c.State = adStateOpen Then
Debug.Print ("Connected") 'This prints!
End If
Set rs = c.Execute(sql)
Debug.Print (rs.RecordCount)
invested_funds = CInt(rs.RecordCount)
End Function
However, I know records exist and the exact same query in SSMS does indeed return records
select [DB].[dbo].[db].[CSRoot]
from [DB].[dbo].[db]
Many records, in fact.
How can this be?
You can get the number of records using the rs.getRows function.
Function invested_funds() As Integer
Dim c As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connectionstring As String
Dim sql As String
connectionstring = "Provider=SQLOLEDB;Data Source=DESKTOP-2TTG3GQ\SQLEXPRESS;" & _
"Initial Catalog=DB;" & _
"Integrated Security=SSPI;"
Set c = New ADODB.Connection
Set rs = New ADODB.Recordset
c.Open connectionstring
sql = "select [DB].[dbo].[db].[CSRoot] " & _
"from [DB].[dbo].[db] "
If c.State = adStateOpen Then
Debug.Print ("Connected") 'This prints!
End If
Set rs = c.Execute(sql)
Dim arr As Variant, n As Integer
arr = rs.GetRows
n = UBound(arr, 2) + 1
'Debug.Print (rs.RecordCount)
Debug.Print n
invested_funds = n
End Function

How do I write to SQL table using excel VBA

I have a SQL table called Audit. There are two fields in this table called UN and CN. My server name is analive and DB is DW_ALL. I am trying to capture in excel the username and computer name that accesses/opens my workbook or sheet then write that audit information to my SQL table.
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
strText = ActiveSheet.Range("b4").Value
''strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")''
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=icl-analive; " & _
"Initial Catalog=DW_ALL;" & _
"User ID=ccataldo;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr
''uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & strDate & ")"''
''uSQL = "INSERT INTO Audit (UN,CN) VALUES (MsgBox Environ("username"), MsgBox Environ("username""''
uSQL = INSERT INTO Audit (UN,CN) VALUES ('MsgBox Environ("username") ', 'MsgBox Environ("username"'))
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
Connection strings can be tricky things. I rely heavily on ConnectionStrings.com to refresh my memory.
Trusted_Connection and User ID are mutually exclusive. Use trusted connection when you want to log onto SQL Server using your Windows account. Username and password are for logging in with a SQL account.
Assuming you want to use your Windows login; try this:
Provider=SQLNCLI11;Server=analive;Database=DW_ALL;Trusted_Connection=yes;
Here is a sample script that writes to an AccessDB. The SQL Should be similar as well as the needed vba statements. I hope it helps
Also it uses DAO and not Addob connection type.
Private Sub thisbetheshitmane()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim tb As DAO.TableDef
Dim vAr As String
Dim i As Integer
Dim y As Integer
Dim InCombined As Boolean
Dim InOpen As Boolean
Dim vbSql As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer
Set db = DBEngine.OpenDatabase("C:\Users\dzcoats\Documents\Microsoft.accdb")
For Each tb In db.TableDefs
If Len(tb.Connect) > 0 Then
tb.RefreshLink
End If
Next tb
Set rst = db.OpenRecordset("SELECT DISTINCT [Table_Name].Defect FROM [Table_Name] WHERE [Table_Name].Defect IS NOT NULL;")
Dim QResult() As Variant
QResult = rst.GetRows(rst.RecordCount)
For a = LBound(QResult, 2) To UBound(QResult, 2)
vAr = QResult(0, a)
Next a
For y = LBound(QResult, 2) To UBound(QResult, 2)
If vAr <> "Defect" And vAr <> vbNullString And vAr <> "" Then
If InCombined = True And InOpen = True Then
vbSql = "UPDATE [Table_Name] SET [Table_Name].Status ='Bad Defect Number' WHERE ((([Table_Name].Defect)='" & vAr & "'));"
db.Execute vbSql
End If
If InCombined = False And InOpen = True Then
vbSql = "UPDATE [Table_Name] SET [Table_Name].Status ='Completed' WHERE ((([Table_Name].Defect)='" & vAr & "'));"
db.Execute vbSql
End If
End If
Next y
rst.Close
Set rs = Nothing
db.Close
Set db = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub

Runtime error 3001 'Arguments are of the wrong type or out of acceptable range...'

I have an Excel table and want to update SQL Server table records' date value (with getdate function) which referred by 12th column of Excel.
My code is as below, but I'm seeing:
Run-time error 3001 Arguments are of the wrong type or out of acceptable range or are in conflict with one another.
In SQL table MODIFIEDDATE field is datetime type, and MAINREF field is integer type.
Private Sub CommandButton2_Click()
Dim conn2 As New ADODB.Connection
Dim rst2 As New ADODB.Recordset
Dim j As Integer
conn2.ConnectionString = "Provider=SQLOLEDB.1;Password=abc;Persist Security Info=True;User ID=sa;Initial Catalog=logodb;Data Source=A3650;Use Procedure for Prepare=1;Auto"
conn2.Open
For j = 0 To 1900
If Sayfa1.Cells(j + 4, 12) = "" Then
Sayfa1.Cells(j + 4, 13) = "empty"
Else
rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & Sayfa1.Cells(j + 4, 12) & "'", conn, 1, 3
rst2.Close
End If
Next j
End Sub
I've tried to change the SQL query like, (CInt(cell.value))
rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & CInt(Sayfa1.Cells(j + 4, 12)) & "'", conn, 1, 3
but, it didn't work.
The ADODB.Recordset object should not be used for an UPDATE query. Execute the SQL statement directly from the ADODB.Connection
Dim conn2 As New ADODB.Connection
conn2.ConnectionString = "Provider=SQLNCLI11;Server=MYSERVER;Database=TMP;UID=sa;password=abc;"
conn2.Open
conn2.Execute "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF=1"
There are a couple of ways you can fulfil your requirements and it seems that you are mixing the two.
One way is to update records one at a time, and to do this you would use the Connection object or, more preferably, the Command object. I say preferably because parameterised commands are a far more robust way of executing your SQL. If you intend to use SQL then it's something you probably ought to read about. The way you would do that is as follows:
Public Sub ParameterisedProcedure()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim v As Variant
Dim j As Integer
'Read the sheet data
v = Sayfa1.Range("L4", "M1904").Value2
'Open the database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Password=abc;" & _
"Persist Security Info=True;" & _
"User ID=sa;" & _
"Initial Catalog=logodb;" & _
"Data Source=A3650;" & _
"Use Procedure for Prepare=1;" & _
"Auto"
conn.Open
'Loop through the values to update records
For j = 1 To UBound(v, 1)
If IsEmpty(v(j, 1)) Then
v(j, 2) = "empty"
Else
'Create the parameterised command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "UPDATE T_015 " & _
"SET MODIFIEDDATE=? " & _
"WHERE MAINREF=?"
prm = cmd.CreateParameter(Type:=adDate, Value:=Now)
cmd.Parameters.Append prm
prm = cmd.CreateParameter(Type:=adInteger, Value:=v(j, 1))
cmd.Parameters.Append prm
cmd.Execute
End If
Next
'Write the updated values
Sayfa1.Range("L4", "M1904").Value = v
'Close the database
Set prm = Nothing
Set cmd = Nothing
conn.Close
End Sub
The other way is to use Transactions and you would indeed use a Recordset for that (ie similar to what you have already done). In this case I'd suggest it is the better way to do it because executing one command at a time (as in the above code) is very slow. A vastly quicker way would be to commit all your updates in one transaction. Like a parameterised command, it's also safe from rogue strings entering your SQL command text. The code would look like this:
Public Sub TransactionProcedure()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmdText As String
Dim v As Variant
Dim j As Integer
'Read the sheet data
v = Sayfa1.Range("L4", "M1904").Value2
'Open the database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Password=abc;" & _
"Persist Security Info=True;" & _
"User ID=sa;" & _
"Initial Catalog=logodb;" & _
"Data Source=A3650;" & _
"Use Procedure for Prepare=1;" & _
"Auto"
conn.Open
'Retrieve the data
Set rs = New ADODB.Recordset
cmdText = "SELECT * FROM T_015"
rs.Open cmdText, conn, adOpenStatic, adLockReadOnly, adCmdText
'Loop through the values to update the recordset
On Error GoTo EH
conn.BeginTrans
For j = 1 To UBound(v, 1)
If IsEmpty(v(j, 1)) Then
v(j, 2) = "empty"
Else
'Find and update the record
rs.Find "MAINREF=" & CStr(v(j, 1))
If Not rs.EOF Then
rs!ModifiedDate = Now
rs.Update
End If
End If
Next
conn.CommitTrans
'Write the updated values
Sayfa1.Range("L4", "M1904").Value = v
'Close the database
rs.Close
conn.Close
Exit Sub
EH:
conn.RollbackTrans
Sayfa1.Range("L4", "M1904").Value = v
rs.Close
conn.Close
MsgBox Err.Description
End Sub

"Application Defined or Object Defined" error in VBA-SQL connection

I am trying to write an Exce-Vba code for SQL connection. The code, first will open the connection to the server, then it will copy a 4 columns of table (Range("C22:G81")) from my Excel-sheet to the SQL-server (I am only trying to send numerical table now as a test, I don't send any column name)
I have been trying to solve a "Application Defined or Object Defined" error quite long time. I get the error for the connection string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName & ";Extended Properties=""Excel 12.0;"
I even tried with another version with password option like strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName & ";Extended Properties=""Excel 12.0; Jet OLEDB:Database Password='passwd';"
But I get the same error. I am quite new in SQL-coding. I wonder if I am missing something important.
Lasly, I don't know if it is related to this error, but I manually created 4 columns in the SQL server for my 4 columns in the Excel. Do I need to write something specific that those 4 columns in the Excel-sheet will find the right columns in the SQL-server?
Thanks in advance...
The code:
Private Sub inlasning()
Dim MyWorkBook As Workbook
Dim rs As New ADODB.Recordset
Dim conn As New ADODB.Connection
Dim ServerName As String, DataBaseName As String, strSQL As String
Set conn = New ADODB.Connection
ServerName = "E45c7642"
DataBaseName = "Tables"
' Specify the OLE DB provider
conn.Provider = "sqloledb"
' Set SQLOLEDB connection properties
conn.Properties("Data Source").Value = ServerName
conn.Properties("Initial Catalog").Value = DataBaseName
' Windows NT authentication.
conn.Properties("Integrated Security").Value = "SSPI"
conn.Open
Dim ValidSheet As Worksheet
Dim HeaderRange As Range
Dim DataRange As Range
Dim ColRange As Range
Dim LastRange As Range
Dim strName As String, strCon As String
strName = ThisWorkbook.FullName
Application.ScreenUpdating = False
Set ValidSheet = ThisWorkbook.Sheets("Sheet2") '
Set HeaderRange = ValidSheet.Range("C20:G21")
Set ColRange = HeaderRange.Find(TheHeader, , , xlWhole)
Set LastRange = ColRange.End(xlDown)
Set DataRange = ValidSheet.Range("C22:G81") ' This is what I am trying to transfer, only numeric values without column names
strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName _
& ";Extended Properties=""Excel 12.0;"
conn.Open strCon
strSQL = "SELECT * FROM [" & ValidSheet.Name & "$" & Replace(DataRange, "$", "") & "];"
rs.Open strSQL, dbclass, adOpenStatic, adLockReadOnly
arrData = rs.GetRows
rs.Close
conn.Close
Set rs = Nothing
Set conn= Nothing
Set ValidSheet = Nothing
End Sub
After getting the same error for the "connection string", I changed the strategy, and I used dbclass procedure to open a connection. So the new code is like below. (I found this coding from a guy, but he is on vacation now, so I can't ask him).
It gets connection (dbclass) properties automatically, which are saved in the main ThisWorkbook. This code doesn't give any error at all, but it doesn't copy the column from the Excel to the database. I tried different versions for the sql-query, like SQL = .... VALUES('result') or SQL = .... VALUES(result), but there is no result again, without error.
Private Sub Testing_Click()
Dim FindColValues() As Double
Dim ValidBook As Workbook
Dim ValidSheet As Worksheet
Dim DataRange As Range
Dim dataa As Range
Application.ScreenUpdating = False
TheSheet = "Sheet2"
Set ValidSheet = Worksheets(TheSheet)
Set DataRange = ValidSheet.Range("C21:C81")
' Below creating an array "result(it)" from the seleced range.
For Each dataa In DataRange
ReDim Preserve result(it)
result(it) = dataa.Value
it = it + 1
Next
' Below is just an alternative array for "in case"
arrData = ValidSheet.Range("C22:G81").Value
SQL = "INSERT INTO Table_test (Column1) VALUES ('result()');"
dbclass.ExecuteSQL SQL
End Sub
Below is dbclass connection properties which is read automatically by the other function:
Private Sub Workbook_Open()
Dim connOk As Boolean
Dim rs As New ADODB.Recordset
Dim MyWorkBook As Workbook
Dim CurSheet As Worksheet
Set dbclass = New clsDB
dbclass.Database = "Tables"
dbclass.ConnectionType = SqlServer
dbclass.DataSource = "E45c7642"
dbclass.UserId = Application.UserName
connOk = dbclass.OpenConnection(False, True)
If connOk = False Then
MsgBox "Cannot connect"
Else
MsgBox "The server is connected"
End If
End Sub
Finally I found the problem for my second code. As I wrote before, in my alternative code (second code), I didn't get any error at all in VBA, but it didn't save my table into the server.
Now I know the reason, because my real value was in "comma" format, but the server saved the value in "dot" format. So I added Str(value) to convert the "comma" value to the "dot" value, and it works now:
....
SQL = "INSERT INTO Table_test (Column1) VALUES (" & Str(result(1)) & ")"
dbclass.ExecuteSQL SQL
End Sub

VB6 ADODB.Recordset RecordCount property always returns -1

I am trying to get some old VB6 code to work with SQL Server Compact.
I can connect, open the database and all seems well. I can run insert select commands which work.
However the ADODB.Recordset RecordCount property always returns -1 even though I can access the Fields and see the data. Changing the CursorLocation = adUseClient causes a problem when executung the SQL (multiple-step operation generated errors).
Option Explicit
Private Const mSqlProvider As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;"
Private Const mSqlHost As String = "Data Source=C:\Database.sdf;"
Private mCmd As ADODB.Command ' For executing SQL
Private mDbConnection As ADODB.Connection
Private Sub Command1_Click()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim DbConnectionString As String
DbConnectionString = mSqlProvider & _
mSqlHost
Set mDbConnection = New ADODB.Connection
mDbConnection.CursorLocation = adUseServer
Call mDbConnection.Open(DbConnectionString)
If mDbConnection.State = adStateOpen Then
Debug.Print (" Database is open")
' Initialise the command object
Set mCmd = New ADODB.Command
mCmd.ActiveConnection = mDbConnection
mCmd.CommandText = "select * from myTestTable"
mCmd.CommandType = adCmdText
Set rs = mCmd.Execute
Debug.Print rs.RecordCount ' Always returns -1 !!
Debug.Print rs.Fields(0) ' returns correct data for first row, first col
Debug.Print rs.Fields(1) ' returns correct data for first row, 2nd col
Debug.Print rs.Fields(2) ' returns correct data for first row, 3rd col
End If
End Sub
Any advice would be gratefully accepted.
Actually the CursorLocation plays a major role in this case. Use rs.CursorLocation = adUseClient to set the cursor location and try.
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
Dim DbConnectionString As String
DbConnectionString = mSqlProvider & _
mSqlHost
Set mDbConnection = New ADODB.Connection
mDbConnection.CursorLocation = adUseServer
Call mDbConnection.Open(DbConnectionString)
If mDbConnection.State = adStateOpen Then
Debug.Print (" Database is open")
' Initialise the command object
Set mCmd = New ADODB.Command
mCmd.ActiveConnection = mDbConnection
mCmd.CommandText = "select * from myTestTable"
mCmd.CommandType = adCmdText
Set rs = mCmd.Execute
Debug.Print rs.RecordCount ' This should now return the right value.
Debug.Print rs.Fields(0) ' returns correct data for first row, first col
Debug.Print rs.Fields(1) ' returns correct data for first row, 2nd col
Debug.Print rs.Fields(2) ' returns correct data for first row, 3rd col
End If
End Sub
That's a result of the type of cursor used to access the data, this post covers the issue and possible fixes.
http://www.devx.com/tips/Tip/14143
EDIT
I apologize for not being more attentive to the fact that you were dealing with Compact. With Compact the situation is similar to the one I referenced, as it uses forward only cursors by default (which do not support row count) but there are two other cursor types available as documented in the link below.
http://support.microsoft.com/kb/272067
From memory with working with VB6/ADO a long time ago the .RecordCount field doesn't return meaningful data until you've moved to the end of the recordset.
rs.MoveLast
rs.MoveFirst
Debug.Print rs.RecordCount
Though with this you'll need to make sure you have the appropriate cursor type (i.e., not forward only).
The only other solution I can think of is to do a separate SELECT COUNT(*) FROM myTestTable, etc but this has issues with the data changing between that call, and the one that actually returns the rows.
With Compact the default cursor attribute is adOpenForwardOnly for improved performance. As such RecordCount is returned as "-1" which means its not available, rather than blank. This is by design because the # of records in a dynamic cursor could change and result in pinging back and forth between the client server to maintain accuracy. However, if the record count is vital try setting it to use adOpenKeyset or adOpenStatic with a server-side cursor.
Check Recordset Property
The follow is result that RecordCount value returned by com.status.live code
+------------------+-------------------+-------------+---------------+--------------+
| CursorTypeEnum|adOpenForwardOnly=0|dOpenKeyset=1|adOpenDynamic=2|adOpenStatic=3|
|CursorLocationEnum| |
+------------------+-------------------+-------------+---------------+--------------+
|adUseServer = 2 | X | O | X | O |
|adUseClient = 3 | O | O | O | O |
+------------------+-------------------+-------------+---------------+--------------+
You may try something like this..
Set rs = mCmd.Execute
rs.MoveFirst
Do Until rs.EOF = true
Debug.Print rs.RecordCount ' Always returns -1 !!
Debug.Print rs.Fields(0) ' returns correct data for first row, first col
Debug.Print rs.Fields(1) ' returns correct data for first row, 2nd col
Debug.Print rs.Fields(2) ' returns correct data for first row, 3rd col
counter = counter + 1
rs.MoveNext
Loop
Here is a solution for you that I used
Dim recordnumber As Long
Dim SalRSrec As New ADODB.Recordset
Set SalRSrec = Nothing
SalRSrec.Open ("SELECT count(*) from SALARY where EMPID= '" & cmb_empid & "' ;"), Dbase, adOpenKeyset, adLockOptimistic
recordnumber = SalRSrec.GetString
MsgBox recordnumber
Replace Set rs = mCmd.Execute with:
set rs = new ADODB.Recordset
rs.Open "select * from myTestTable", mDBConnection, adOpenDynamic, adLockOptimistic
The adOpenDynamic will allow a forward/backward read through to get your recordcount.
Try using following code if still returns -1
Set Conn = createobject("ADODB.connection")
Set Rs = createobject("ADODB.recordset")
Conn.Open "DSN=DSN_QTP"
'Rs.Open "Select * From orders",Conn,adOpenDynamic,adLockBatchOptimistic
Rs.Open "Select * from [QTP-Table]",Conn,1 'Use either 1 or 3
'I tried using adopendynamic but it still returned -1. Using 1 it gave me correct count. 'Though I am using this code in QTP (Vbscript) same should work for VB6 also.
msgbox Rs.RecordCount
Below code might help you,
set conn = CreateObject("ADODB.Connection")
conn.open "<connection string>"
set rs = CreateObject("ADODB.Recordset")
sql = "SELECT columns FROM table WHERE [...]"
rs.open sql,conn,1,1
if not rs.eof then
nr = rs.recordcount
response.write "There were " & nr & " matches."
' ... process real results here ...
else
response.write "No matches."
end if
rs.close: set rs = nothing
conn.close: set conn = nothing
Set cn = CreateObject("ADODB.Connection")
strVerb = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\test.accdb"
tab1 = "tabelle1"
strSQL = "SELECT Count(*) FROM " & tab1
Debug.Print strSQL
cn.Open strVerb
Set rs = cn.Execute(strSQL)
Debug.Print rs.Fields(0)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
you must set the CONNECTIOn to aduseClient, no recordset
and be carefoul to set only a new connection, if you use the same connection in your proyect, you can get other errors.
CRAETE A NEW CONNEXTION with aduseclient
Dim Sql As String
Dim CnCommand As New ADODB.Connection
On Error GoTo VerError:
Dim Comando As ADODB.Command
Set Comando = New ADODB.Command
CnCommand.ConnectionString = Cn.ConnectionString 'your exist connection in application
CnCommand.Open
CnCommand.CursorLocation = adUseClient
Set Comando.ActiveConnection = CnCommand
'Comando.ActiveConnection.CursorLocation = adUseClient
Comando.Parameters.Append Comando.CreateParameter("#Usuario", adInteger, adParamInput, , V_General.Usuario.Codigo)
Comando.CommandType = adCmdStoredProc
Comando.CommandText = "SP_Contratac"
Dim Rs As Recordset
Set Rs = New ADODB.Recordset
Set Rs = Comando.Execute()
This following code returns the recortcount exactly...
Public Sub test()
Dim cn As New ADODB.Connection()
Dim sPath As String = Application.ExecutablePath
sPath = System.IO.Path.GetDirectoryName(sPath)
If sPath.EndsWith("\bin") Then
sPath = sPath.Substring(0, Len(sPath) - 4)
End If
Dim DbConnectionString As String
DbConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" & sPath & "\students.mdb"
cn.ConnectionString = DbConnectionString
cn.Open()
Dim rs As New ADODB.Recordset()
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
rs.Open("select * from students", cn)
MsgBox(rs.RecordCount)
rs.ActiveConnection = Nothing
cn.Close()
End Sub

Resources