473,403 Members | 2,183 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

How to use excel VBA to SQL query and compare data?

I have the below code, which queries a database and compares the recordset against my variable 'StockCode'.

This is not currently working and if i add the line 'Msgbox rs.recordcount' then this comes back with the message '-1'.
However, when i add the line 'ActiveSheet.Range("A5").CopyFromRecordset (rs)' then all records are pasted in to my excel spreadsheet. can someone see what i am doing wrong?

Expand|Select|Wrap|Line Numbers
  1. Sub SubmitInterchange()
  2.  
  3. Dim oConn As Object
  4. Dim sSQL As String
  5. Set rs = New ADODB.Recordset
  6. Dim strSql As String
  7.  
  8. Set oConn = CreateObject("ADODB.Connection")
  9. oConn.Open = "Provider=sqloledb;" & _
  10. "Data Source=############;" & _
  11. "Initial Catalog=SysproCompany2;" & _
  12. "User Id=##;" & _
  13. "Password=#######"
  14.  
  15. strSql = "SELECT StockCode FROM InvMaster"
  16. Set rs.ActiveConnection = oConn
  17. rs.Open strSql
  18.  
  19. MsgBox rs.RecordCount
  20.  
  21.  
  22. 'ActiveSheet.Range("A5").CopyFromRecordset (rs)
  23.  
  24. RowCount = rs.RecordCount
  25. Dim alldata() As Variant
  26. alldata = rs.GetRows(RowCount)
  27.  
  28. Dim switch As Boolean
  29. Dim StringVal As String
  30.  
  31. switch = False
  32.  
  33.  
  34. For n = 10 To 109
  35.  
  36.        StockCode = Worksheets("Interchange_Insert").Cells(n, 4).Value
  37.        Barcode = Worksheets("Interchange_Insert").Cells(n, 5).Value
  38.  
  39. If StockCode > 1 Then
  40.  
  41. For i = 0 To RowCount - 1
  42.  
  43.        StringVal = CStr(alldata(0, i))
  44.        StringVal = Trim(StringVal)
  45.  
  46.     If StringVal = StockCode Then
  47.        switch = True
  48.     End If
  49.  
  50. Next i
  51.  
  52.     If switch = False Then
  53.                 MsgBox StockCode & " is an invalid stock code"
  54.                 Exit For
  55.     End If
  56.  
  57. switch = False
  58.  
  59. MsgBox "StockCode:" & StockCode & "  Barcode:" & Barcode & ""
  60. sSQL = "INSERT INTO InvMaster(StockCode, DrawOfficeNum) VALUES ('" & StockCode & "', '" & Barcode & "')"
  61. oConn.Execute sSQL
  62. End If
  63.  
  64. Next n
  65.  
  66. oConn.Close
  67. Set oConn = Nothing
  68.  
  69. End Sub
Mar 10 '11 #1
5 7941
MikeTheBike
639 Expert 512MB
Hi

If you add these lines

rs.CursorType = adOpenDynamic
rs.LockType = adLockOptimistic

before you open the record set then rs.RecordCount will return the correct value. It is good proctice (IMHO) to always specify these perameters.

The other way of forcing the RecordCout property with a Dymamic type record set is

rs.MoveLast

This sets the count propery (don't forget to rs.MoveFirst afterwards!).

HTH

MTH
Mar 11 '11 #2
thanks for that Mike!
another line that will need addressing is where i have:
If StringVal = StockCode then
Switch = True
End If

this just does not work, everytime i run the macro it says the stockcode is invalid even though it exists in the table.

thank you
Mar 11 '11 #3
MikeTheBike
639 Expert 512MB
The only thing I can suggest is you put this line

Msgbox StringVal & " = " & StockCode & " ?"

imediatly before

If StringVal = StockCode Then

and see if you have what you think you have?

Pehaps this may do it

If UCase(Trim(StringVal)) = UCase(Trim(StockCode)) Then

??


MTB
Mar 11 '11 #4
hi Mike

I have tried both of your suggestions and the macro is working exactly as it was...
It still displays -1 as the recordcount and does not match the StockCode with StringVal.

I don't think the data is looping as StringVal always returns nothing

thank you
Mar 11 '11 #5
MikeTheBike
639 Expert 512MB
Hi

Well what can I say, although I haven't connected to an SQL DB, only Access, but this always works for me
Expand|Select|Wrap|Line Numbers
  1. Sub test()
  2.     Dim oConn As Object
  3.     Dim rs As New ADODB.Recordset
  4.     Dim strSql As String
  5.     Dim ConStr As String
  6.     Dim alldata() As Variant
  7.  
  8.     Set rs = New ADODB.Recordset
  9.     Set oConn = CreateObject("ADODB.Connection")
  10.  
  11.     ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data "
  12.     ConStr = ConStr & "Source=\\bfpdc\cesaccess$\CESTimesheetsDB\Data\CES Timesheets_BE ST6.mdb;"
  13.     ConStr = ConStr & "Persist Security Info=False"
  14.  
  15.     oConn.Open ConStr
  16.  
  17.     If oConn.State = adStateOpen Then
  18.         strSql = "SELECT * FROM tblTickets ORDER BY TicketNo"
  19.         With rs
  20.             .CursorLocation = adUseClient
  21.             .CursorType = adOpenDynamic
  22.             .LockType = adLockReadOnly
  23.             .Source = strSql
  24.             .ActiveConnection = oConn
  25.             .Open
  26.         End With
  27.  
  28.  
  29.         alldata = rs.GetRows()
  30.  
  31.         MsgBox UBound(alldata, 2) & "  :  " & rs.RecordCount
  32.         MsgBox alldata(2, 0)
  33.  
  34.         rs.Close
  35.         oConn.Close
  36.     End If
  37.     Set rs = Nothing
  38.     Set oConn = Nothing
  39.  
  40. End Sub
Again, I have never used the 'rs.GetRows()' method, but you will note that this line
Expand|Select|Wrap|Line Numbers
  1. MsgBox UBound(alldata, 2) & "  :  " & rs.RecordCount
displays the number of records and the number -1 (at least in my case), so you can get ther record count from the upper bound property of the Array if all else fails.

There are other ways of doing what (I think) you are doing. I would do it something like this where you don't need to know the number of records by using the recordset EndOfFile property
Expand|Select|Wrap|Line Numbers
  1. Sub SubmitInterchange()
  2.  
  3.     Dim oConn As Object
  4.     Dim sSQL As String
  5.     Dim rs As New ADODB.Recordset
  6.     Dim strSql As String
  7.  
  8.     Set oConn = CreateObject("ADODB.Connection")
  9.     oConn.Open = "Provider=sqloledb;" & _
  10.     "Data Source=############;" & _
  11.     "Initial Catalog=SysproCompany2;" & _
  12.     "User Id=##;" & _
  13.     "Password=#######"
  14.  
  15.     strSql = "SELECT StockCode FROM InvMaster"
  16.     Set rs.ActiveConnection = oConn
  17.  
  18.     With rs
  19.         .CursorLocation = adUseClient
  20.         .CursorType = adOpenDynamic
  21.         .LockType = adLockReadOnly
  22.         .Source = strSql
  23.         .ActiveConnection = oConn
  24.         .Open
  25.     End With
  26.  
  27.     Dim switch As Boolean
  28.     Dim StringVal As String
  29.  
  30.     switch = False
  31.  
  32.     For n = 10 To 109
  33.  
  34.         StockCode = Trim(Worksheets("Interchange_Insert").Cells(n, 4).Value)
  35.         Barcode = Worksheets("Interchange_Insert").Cells(n, 5).Value
  36.  
  37.         If StockCode > 1 Then
  38.             Do Until rs.EOF
  39.                 StringVal = CStr(rs(0))
  40.                 StringVal = Trim(StringVal)
  41.                 If UCase(StringVal) = UCase(StockCode) Then
  42.                    switch = True
  43.                 End If
  44.                 rs.MoveNext
  45.             Loop
  46.             rs.MoveFirst
  47.  
  48.             If switch = False Then
  49.                 MsgBox StockCode & " is an invalid stock code in line " & n & "!"
  50.             Else
  51.                 MsgBox "StockCode:" & StockCode & "  Barcode:" & Barcode & ""
  52.                 sSQL = "INSERT INTO InvMaster(StockCode, DrawOfficeNum) VALUES ('" & StockCode & "', '" & Barcode & "')"
  53.                 oConn.Execute sSQL
  54.             End If
  55.         End If
  56.         switch = False
  57.     Next n
  58.  
  59.     rs.Close
  60.     oConn.Close
  61.     Set oConn = Nothing
  62.  
  63. End Sub
  64.  
Hope this is of some use, but I do not know why you do not get the correct RecordCount value. Perhaps some one else could enlighten us both?

MTB
Mar 14 '11 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Lukman | last post by:
Hi, Do you know how to display ASP.NET result (database result from ADO.NET) using Excel in IE ? Thanks,
2
by: Don Wash | last post by:
Hi All! I've been searching everywhere for a simple sample of producing a bar graph using CrystalReport by specifying SQL Query, and I've found none of it! I find so many complex samples with so...
14
by: pmud | last post by:
Hi, I need to use an Excel Sheet in ASP.NET application so that the users can enter (copy, paste ) large number of rows in this Excel Sheet. Also, Whatever the USER ENETRS needs to go to the...
0
by: Joe | last post by:
I have a small problem using Excel templates. I've got a VB .NET class library that will create an Excel spreadsheet. It's called from a windows form and is passed an array containing the data...
4
by: somanyusernamesaretakenal | last post by:
What I am trying to achieve: Basically I have generated a report in access. This report needs to be updated using excel. (Updating the new data, not changing existing data) What I did was I...
0
by: liam_jones | last post by:
I'm very new to Python, well IronPython to precise, and have been having problems when using Excel. The problem I'm having is the closing of my Excel object. I'm able to successfully quit the...
2
by: sfeinst | last post by:
I am trying to access Excel spreadsheets to modify data from a VB.NET application. If I have an object defined as: Public Class Test Private _excel As Microsoft.Office.Interop.Excel.Application...
5
atljpe
by: atljpe | last post by:
In Excel: My query can only be refreshed if your using z: as your drive header. I want to change it so anyone can refresh this query wether they're using x, y, or z for their drive header: The...
1
by: vai | last post by:
hi all, i'm developing a stock management system. in this system i'm developing a billing system which on daily & monthly basis. i'm using ms-acess database as backend & visual baic as front end....
2
by: silversubey | last post by:
Hello all. I have an excel query that pulls data from a SQL database. I have 2 parameters that represent the and of a between criteria. Here is the query. SELECT CltDue.CDClientName ,...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.