Requesting Assistance with a macro Using Range button for searching through SQL Server database

SUGGESTED

Good Morning,

I am new to VBA and having an issue with a macro which a form. I have added a range button that will accept Two(2) values entered by a user in a and then access data from the database then add it to a Filter List.   Currently working on adding functionality for the "Add Range" button. That will take the values entered in "Range1.Text" & "Range2.Text" and find all the item numbers between them, then Add them to the "Filters Added" textbox, was working on a loop,will need to add a connection to database as well. I am not sure if I am not setting up connection to the database properly as nothing is being printed in the Filters Added textbox.

Please Let me know if you have any suggestions on how to approach this issue.  I have attached some snippets of the Add RangeButton Sub below:

Private Sub AddRangeButton_Click()

'Use Range1.Text & Range2.Text, add items to AddFilter list


If btnIgnoreList.Caption = "Add Range" Then
If Trim(Range1.Text) <> "" And Trim(Range2.Text) <> "" Then

Set Connection = New ADODB.Connection
Set Recordset = New ADODB.Recordset
Dim doesExist As Boolean
'query = "INSERT INTO [dbo].[ignore_list]([itemno]) VALUES ('" & ilItemno & "')"
query = "SELECT ITEMNO FROM [SHLDAT].[dbo].[ICITEM] WHERE ITEMNO BETWEEN " & Range1.Value & "AND" & Range2.Value & " "
Connection.connectionString = connectionString
Connection.ConnectionTimeout = 10
Connection.Open
Recordset.Open query, Connection
Recordset.ActiveConnection = Nothing
Connection.Close
'Call getItemList



lbFilter.AddItem Range2.Value
' addToIgnoreList (txtIgnoreList.Text)

End If

End If


'SELECT ITEMNO FROM [SHLDAT].[dbo].[ICITEM] WHERE ITEMNO BETWEEN " & Range1.Value & "AND" & Range2.Value & "ORDER BY ITEMNO DESC

' Dim dbs As DAO.Database
' Dim rst As DAO.Recordset
' Dim rstFiltered As DAO.Recordset
' Dim TempItemNo As String



' Dim Connection As ADODB.Connection
' Dim Recordset As ADODB.Recordset
' Dim query As String
'Dim Temp As Variant


' Set Connection = New ADODB.Connection
' Connection.Open
' Set Recordset = New ADODB.Recordset


' Set dbs = New DAO.Database
'
' Set dbs = CurrentDb
'
'
' Set rest = dbs.OpenRecordset("SELECT ITEMNO FROM [SHLDAT].[dbo].[ICITEM] WHERE ITEMNO BETWEEN " & Range1.Value & "AND" & Range2.Value & "ORDER BY ITEMNO DESC")
'
' Do While Not rst.EOF
' TempItemNo = rst!itemno
'
' rst.filter = "ItemNo:'" & TempItemNo & " '"
' Set rstFiltered = rst.OpenRecordset
'
'
' Do While Not rstFiltered.EOF
' rstFiltered.Edit
' rstFiltered!ToBeVisited = True
' rstFiltered.Update
' rstFiltered.MoveNext
' Loop
'
' Exit Do
' rst.MoveNext
'
'
' Loop
'
' rstFiltered.Close
' rst.Close
'
' Set rstFiltered = Nothing
' Set rst = Nothing





' query = "SELECT itemno FROM [SHLDAT].[dbo].[ICITEM] WHERE itemno BETWEEN 'Range1.Value' AND 'Range2.Value'"
' Connection.connectionString = connectionString
' Connection.ConnectionTimeout = 10
' Connection.Open
' Recordset.Open query, Connection

' If AddRangeButton.Caption = "Add Range" Then
'
' If Trim(Range1.Text) <> "" And Trim(Range2.Text) <> "" Then
'
'
'
' Recordset.Open (query)
'DoCmd.OpenQuery "query"

'Set Recordset = Connect.Execute(query)


' For i = 0 To lbFilter.ListCount - 1
'
' Temp = Trim(Range1.Value)
'
'
'
'
' If Trim(Range1.Value) >= Temp And Trim(Range2.Value) < Temp Then
'
'
' lbFilter.List(i) = Temp


' If lbFilter.List(i) = Trim(Range1.Value) Or Trim(Range2.Value) Then
'
' GoTo DoNotAddDuplicates
'
'
' End If

' lbFilter.AddItem Recordset
'End If
'Next i
'lbFilter.AddItem Temp



'DoNotAddDuplicates:
' Range1.Text = "" Or Range2.Text = ""
' End If
'
' End If
'
'
' Recordset.Close

' Recordset.ActiveConnection = Nothing

' Connection.Close



      

  • 0
    A couple of pointers. Make sure that you turn Option Explicit on at the top of all of your VBA modules. Next, add error trapping. Third - ITEMNO in ICITEM is unformatted and can be different than the formatted item number so watch out for that. Finally, item numbers are alpha numeric so your SQL string needs to surround the values with apostrophes. e.g.

    query = "SELECT ITEMNO FROM [SHLDAT].[dbo].[ICITEM] WHERE ITEMNO BETWEEN '" & Range1.Value & "' AND '" & Range2.Value & "' "

    When I'm working with SQL calls I would typically follow the line above with:

    debug.print query

    That will make the SQL appear in the immediate window and then I can copy/paste the query into SQL Server Management Studio to see if the database any any issues with what I wrote.
  • 0 in reply to Django

    Thank you for responding,

    I made the suggested change to the query, I knew there was something off with the syntax but I wasn't sure what I had left out. I'm still having trouble getting the itemno to display in the "Filters Added" Textbox. I'm not 100% sure if I have set up the connection to Sql Server correctly..  I am trying to get the query to execute then add each item number between the Range specified by the user to the "Filters Added" textbox. As it is right now, when i click "Add Range" Nothing happens, no error pops up either.

    Attached is an update on the code.

  • 0 in reply to GBrown2615
    Pre-script: don't name your variables the same as object/class names. You'll increase your chance of introducing bugs

    You're not doing anything with the results of the recordset. You're opening the connection, running the query to get the records and closing the connection. I see that you're thinking of using a dis-connected recordset but there's not any reason unless you're expecting a huge amount of records (tens of thousands (in which case your design won't work)).

    Something like this:

    MyRecordset.Open...
    while not MyRecordSet.EOF
    lbFilter.AddItem trim$(MyRecordSet.Fields("ITEMNO").value)
    MyRecordSet.MoveNext
    wend
    MyRecordSet.Close
  • 0 in reply to Django
    SUGGESTED
    Here is a link to a small project that interacts with pricing information using the Accpac COM API
    www.dropbox.com/.../UpdatePrice.avb
  • 0 in reply to Django

    Ok so I changed the variable names like you suggested. I was following the naming convention used in other parts of the code. So instead of Connection or Recordset I just named them "conn" and "rec". I see, so I was closing the record before it did anything with the results. Still not displaying the itemno's in the "Filters Added" textbox. 

    Attached is a code snippet with the changes:

     

  • 0 in reply to GBrown2615
    Can you run the query in SQL Server Management Studio to see what the database is returning?
  • 0 in reply to Django

    Morning,

    Yes, I can. The query works when I run it in SQL Server. Here is the result shown in Code snippet. 

  • 0 in reply to GBrown2615
    If you use breakpoints, does your code get to the lbFilters.additem line of code?
  • 0 in reply to Django

    Ok I used some breakpoints and opened up the immediate window and locals window. As you can see the correct values are being placed in the query. When it gets to the lbFilter.Additem Trim$(rec.Fields("ITEMNO").Value   line of code. I encounter this runtime error "3265".

  • 0 in reply to GBrown2615
    Now you're dealing with an issue where the field that you're referencing doesn't exist. What version of ADO did you include in your macro? Can you check rec.recordcount after you open the recordset?
  • 0 in reply to Django

    Yes, that's what I figured it was saying but that doesn't make sense as the fields are there in the Sql Server database. As for references, ADO 6.1 is referenced. Also I placed a line after the rec.Open "count = rec.RecordCount" . Count is returning empty or Zero(0).Code Snippet Attached

  • 0 in reply to GBrown2615
    Change your ADO selection to version 2.8. And get rid of DAO unless you need it for MS Access. In spite of the higher version number 6.1 is very old. Otherwise there's something fundamental missing that I can't see. Post your connection string.
  • 0 in reply to Django

    Connection String code snippet:

    Sub setConnectionString()

       Dim dbName As String

       dbName = mDBLinkCmpRW.Session.CompanyID

       connectionString = "Provider=SQLOLEDB;Data Source=" & Trim(txtIpAddress.Text) & ";Initial Catalog=" & dbName & ";User ID=" & Trim(txtUsername.Text) & ";Password=" & Trim(txtPassword.Text) & ";"

    End Sub

  • 0 in reply to GBrown2615
    Have you confirmed that your connection is open when you try to run the query? Try running a different query - something like select count(*) as CNT from ICITEM. That will return a value even if there are zero records so your result set should be returning one record.

    In one of your screenshots you're querying SHLDAT for sample data item numbers. In another screenshot you're querying SHLDAT for four digit numeric numbers. Is SHLDAT a sample database or a live database?

    Try taking the filter out: select ITEMNO from ICITEM

    And make sure that your connection string is connecting to SHLDAT. Remove the SHLDAT.dbo out of your query because if you connect to a different database then your query might not be pulling from the database that you're expecting.
  • 0 in reply to Django

    It is the live database. That's how some of the itemno's are in the table. I am not sure why some of them are numeric while most of them are alpha numeric.  I'm also attaching a code snippet of the ignore list buttons. Those work and data is pulled from that table so I'm not sure why it isn't working for the Filter list

  • 0 in reply to GBrown2615
    Your insert and delete queries won't return a recordset so there's no comparison.

    Remove the filter from your query and remove the fully qualified table name and ownership from the query. Trim it down to SELECT ITEMNO FROM ICITEM. or SELECT TOP 10 ITEMNO FROM ICITEM if you have a large number of items.
  • 0 in reply to GBrown2615
    1. All Item numbers in Sage are alphanumeric
    2. Your screenshot is showing items with leading spaces, you need to code for that