Multiple OR in SQL string Variable, VBA - sql

I am using a bit a code to Adjust form length and an SQL variable to modify the names that show up in a Combobox. I want to make sure that the names in the Comboboxes above the one that is being worked on, do not show any names.
So if Combo1 has 40 names then Combo2 will only have 39 and so on.
My problem seems to be when I use multiple "OR" within the WHERE Clause of the SQL String. Can anyone advice?
Private Sub Worker3_Change()
Dim Worker4STR As String
'Shows Worker 4
Me.Worker4.RowSource = ""
Worker4STR = "SELECT T1Workers.NonUserID, T1Workers.[FirstName] & "" "" & [LastName] AS FullName FROM T1Workers WHERE T1Workers.NonUserID <>" & _
Me.Worker1.Value & " OR " & Me.Worker2.Value & " Or " & Me.Worker3.Value
Me.Worker4.RowSource = Worker4STR
Me.Worker4.AllowValueListEdits = False
Me.Worker4.ColumnCount = 2
Me.Worker4.ColumnWidths = "0, "
Me.Worker4.Visible = True
Me.Activity4.Visible = True
Me.w4a1s.Visible = True
Me.w4a1d.Visible = True
Me.w4a1o.Visible = True
Me.w4a2s.Visible = True
Me.w4a2o.Visible = True
Me.w4a2d.Visible = True
Me.w4a3s.Visible = True
Me.w4a3o.Visible = True
Me.w4a3d.Visible = True
Me.w4a4s.Visible = True
Me.w4a4o.Visible = True
Me.w4a4d.Visible = True
Me.w4a5s.Visible = True
Me.w4a5o.Visible = True
Me.w4a5d.Visible = True
Me.InsideHeight = 1440 * 4.6
End Sub
Thank you in Advance.
-Matt

Your clause:
X <> A OR B OR C
Is not valid SQL. You can use NOT IN instead:
"WHERE T1Workers.NonUserID NOT IN (" & _
Me.Worker1.Value & " , " & _
Me.Worker2.Value & " , " & _
Me.Worker3.Value & " ) "
Note that if the values are strings they at a minimum need to be enclosed in quotes. A much better solution is to use SQL parameters instead, but I do not know if that's possible with whatever Worker4 is.

Related

Why I Cant set the FilterOn property in form_open?

I try to set a filter of an continuous form in access vba. This is the code I use:
Private Sub Form_Open(Cancel As Integer)
Dim filter As String
filter = "1 = 0" ' "1=0" is just for testing purpurses
Me.filter = filter
Me.FilterOn = True
Debug.Print Me.FilterOn & "; " & Me.filter
end sub
The output is:
False; 1 = 0
and the filter is not used.
Why does this not work? And is there a way to set and activate the filter before the form is shown?
I found out that the reason is. I use a framework where I set the recordsource later. While there is no recordsource, "Me.FilterOn = True" simply does not work. The following code does work:
Private Sub Form_Open(Cancel As Integer)
Me.RecordSource = "select * from MyTable"
Dim filter As String
filter = "1 = 0" ' "1=0" is just for testing purpurses
Me.filter = filter
Me.FilterOn = True
Debug.Print Me.FilterOn & "; " & Me.filter
end sub
and the output is:
True; 1 = 0

Dlookup in side of a Loop Is it possible?

I am "creating" my first loop, I copied code and am trying to get it to work. I have the loop functioning but when I try to do a Dlookup in the middle of the loop it does not work.
I am sure there are some ways to make this code work better, Just trying to retrieve dynamic data for the body of my email.
Here is the relevant part of the loop.
strSQL = "SELECT * FROM emailbody Where EmailMainID = " & Me.EmailMainID
Set rs = CurrentDb.OpenRecordset(strSQL)
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
LookupInfo = rs.Fields("beforetable") & "-" & rs.Fields("beforefield") 'Get Table and Field to lookup
LookupLen = Len(LookupInfo) 'Find how many letters are in the string
SubtractLen = InStr(1, [LookupInfo], "-") ' Find the number of letters to the left
RightCut = LookupLen - SubtractLen ' Find how many are to the right
Table = Left([LookupInfo], InStr(1, [LookupInfo], "-") - 1) ' Set the table value
Field = Right([LookupInfo], RightCut) ' Set the Field Value
InfoInsert = DLookup("Table", "Field", TeamDetailsID = 39)
FreshData = rs.Fields("emailbodyid") & " " & rs.Fields("bodycontent")
LongEmail = EmailMe & FreshData
EmailMe = LongEmail
FreshData = ""
LongEmail = ""
.MoveNext
Wend
End If
.Close
End With
it should be:
InfoInsert = DLookup("Table", "Field", "TeamDetailsID = 39")
or, if you use a variable
InfoInsert = DLookup("Table", "Field", "TeamDetailsID = " & idteam)
So I my most recent test tells me my difficulty is not the loop.
I tested the code this way (Yes I had the field and the table mixed up in the above example)
I get the result in Test2 But not Test1
Dim Table As String
Dim Field As String
Table = TeamDetails
Field = DepartDate
test2 = DLookup("DepartDate", "TeamDetails", "TeamDetailsID = 39")
MsgBox test2
test1 = DLookup("Field", "Table", "TeamDetailsID = 39")
MsgBox test1

How to fix 'Undefined function 'xxx' in expression' (Excel Function in SQL Query)

I am trying to call an Excel function to a SQL query, but I keep getting the same error : "Undefined function xxx in expression".
I'm working with Excel only due to customer choices.
I've checked if references were missing,
My function is in a valid Module wiht Option Explicit, and it is declared as Public.
And i made sure I had a return value.
Thank you for your time
There is my function
Public Function CalculRamasseCarriste(ByVal lng_QTE As Integer, ByVal str_CodeArticle As String, ByVal lng_QTEmax As Integer) As Boolean
Static lng_cumulQTE As Integer
Static str_Text As String
Static bln_Prendre As Boolean
If str_Text = "" Then
str_Text = str_CodeArticle
ElseIf str_Text <> "" Then
If str_Text <> str_CodeArticle Then
str_Text = str_CodeArticle
lng_cumulQTE = 0
End If
End If
lng_cumulQTE = lng_cumulQTE + lng_QTE
If lng_cumulQTE < lng_QTEmax Then
CalculRamasseCarriste = True
bln_Prendre = True
ElseIf lng_cumulQTE >= lng_QTEmax And bln_Prendre = True Then
CalculRamasseCarriste = True
bln_Prendre = False
Else
CalculRamasseCarriste = False
End If
End Function
And there is my query :
Return_Qry_Ramasse = "SELECT T1.[Adresse], T1.[N° Support], T1.[Code_Article], T1.[Libellé_article] " & _
" FROM [V_Stock$] as T1 " & _
" LEFT JOIN [Cmd$] as T2 on T1.[Code_Article] = T2.[Code_Article] " & _
" WHERE CalculRamasseCarriste(T1.[Nb Box-Colis / Pal], T1.[Code_Article], T2.[UVC_cmd])= True " & _
" ORDER BY [Code_Article], [Adresse], [N° Support]"

SQL Server (specific) table not updating

I am having a really strange issue with classic asp insert/update that worked flawlessly for years and was never altered. Out of the blue, the table is no longer updating or taking new records. The code does not throw any errors and the SQL Server log shows no errors either. Other tables in the same database work fine so I can insert and update without issues.
Is there a way to find out what is happening with this table or whether it is locked for some reason. I restarted SQL Server and web application, even the server and no luck.
I updated the table directly in SQL Server and it updates and inserts new records fine.
I used the same code on another table and was able to update records.
Can someone please point me in the right direction as I am out ideas on what may be causing this.
Thanks in advance.
Here is the code:
<%
' *** Edit Operations: (Modified for File Upload) declare variables
Dim MM_editAction
Dim MM_abortEdit
Dim MM_editQuery
Dim MM_editCmd
Dim MM_editConnection
Dim MM_editTable
Dim MM_editRedirectUrl
Dim MM_editColumn
Dim MM_recordId
Dim MM_fieldsStr
Dim MM_columnsStr
Dim MM_fields
Dim MM_columns
Dim MM_typeArray
Dim MM_formVal
Dim MM_delim
Dim MM_altVal
Dim MM_emptyVal
Dim MM_i
MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (UploadQueryString <> "") Then
MM_editAction = MM_editAction & "?" & Server.HTMLEncode(UploadQueryString)
End If
' boolean to abort record edit
MM_abortEdit = false
' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: (Modified for File Upload) set variables
If (CStr(UploadFormRequest("MM_insert")) = "update") Then
MM_editConnection = MM_ar_inventory_STRING
MM_editTable = "Artists"
MM_editRedirectUrl = "artists_add.asp?status=ok"
MM_fieldsStr = "ArtistName|value|WebsiteStatus|value|Biography|value|Notes|value|ImageFileName|value|ModifiedBy|value|DT|value|IpAddress|value"
MM_columnsStr = "ARTST_Artist|',none,''|ARTST_WebsiteStatus|',none,''|ARTST_Biography|',none,''|ARTST_Notes|',none,''|ARTST_ArtistImageFileName|',none,''|ARTST_ModifiedBy|',none,''|ARTST_LastModified|',none,NULL|ARTST_LastModifiedIP|',none,''"
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(UploadFormRequest(MM_fields(MM_i)))
Next
' append the query string to the redirect URL
If (MM_editRedirectUrl <> "" And UploadQueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And UploadQueryString <> "") Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & UploadQueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & UploadQueryString
End If
End If
End If
%>
<%
' *** Insert Record: (Modified for File Upload) construct a sql insert statement and execute it
Dim MM_tableValues
Dim MM_dbValues
If (CStr(UploadFormRequest("MM_insert")) <> "") Then
' create the sql insert statement
MM_tableValues = ""
MM_dbValues = ""
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_formVal = MM_fields(MM_i+1)
MM_typeArray = Split(MM_columns(MM_i+1),",")
MM_delim = MM_typeArray(0)
If (MM_delim = "none") Then MM_delim = ""
MM_altVal = MM_typeArray(1)
If (MM_altVal = "none") Then MM_altVal = ""
MM_emptyVal = MM_typeArray(2)
If (MM_emptyVal = "none") Then MM_emptyVal = ""
If (MM_formVal = "") Then
MM_formVal = MM_emptyVal
Else
If (MM_altVal <> "") Then
MM_formVal = MM_altVal
ElseIf (MM_delim = "'") Then ' escape quotes
MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
Else
MM_formVal = MM_delim + MM_formVal + MM_delim
End If
End If
If (MM_i <> LBound(MM_fields)) Then
MM_tableValues = MM_tableValues & ","
MM_dbValues = MM_dbValues & ","
End If
MM_tableValues = MM_tableValues & MM_columns(MM_i)
MM_dbValues = MM_dbValues & MM_formVal
Next
MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"
If (Not MM_abortEdit) Then
' execute the insert
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_editConnection
MM_editCmd.CommandText = MM_editQuery
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
If (MM_editRedirectUrl <> "") Then
Response.Redirect(MM_editRedirectUrl)
End If
End If
End If
%>
I notice that UploadQueryString is undefined so if you add this as the fist line
<%OPTION EXPLICIT%>
I guess that you will get some meaningful error messages
The craziest solution to the problem that totally seems unrelated was to disable Symantec Endpoint Protection (Network Protection) and it worked for a reason I cannot possibly explain! Thank you all for the suggestions above.

Error when I set a radio button to be checked by default

I have a radio button in my VB.NET dll that I wan't to be checked by default. There is a total of 3 radio buttons in this group. Under its properties I set Checked = true. I verified the code was there, this is all the form generated code for the radio button:
Me.rdbProductPC.AutoSize = True
Me.rdbProductPC.Checked = True
Me.rdbProductPC.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdbProductPC.Location = New System.Drawing.Point(49, 12)
Me.rdbProductPC.Name = "rdbProductPC"
Me.rdbProductPC.Size = New System.Drawing.Size(45, 17)
Me.rdbProductPC.TabIndex = 1
Me.rdbProductPC.TabStop = True
Me.rdbProductPC.Text = "P&&C"
Me.rdbProductPC.UseVisualStyleBackColor = True
For some reason I get this error when I start the application:
An error occurred creating the form. See Exception.InnerException for details. The error is: ExecuteReader requires an open and available Connection. The connection's current state is closed.
Nothing has changed besides the one line adjusting the checked value. Any idea what could be causing this?
This is the code for my GetProducts() method. The error arises after the call to ExecuteReader() but I cannot see the code for this. If my g_strSQL = pc_mis_busunit_product_relate_summary it executes fine. But when g_strSQL = pc_mis_busunit_product_relate_summary '','','N' it errors out.
That being said, if I leave the radio button unchecked by default and then check it later while the program is running it will go into this same method and g_strSQL will look like pc_mis_busunit_product_relate_summary '','','N' and it will work fine.
Private Sub GetProducts(ByVal ProductList As ListBox)
Dim g_strSQL As String
ProductList.Items.Clear()
lstProductSel.Items.Clear()
lstProduct.Enabled = True
g_strSQL = String.Empty
objcmd.Connection = ControlConnection
'Clear location combo box
Select Case intProduct
Case Product.Summary
g_strSQL = g_strSQL & "pc_mis_busunit_product_relate_summary "
Case Product.Detail
g_strSQL = "SELECT DISTINCT b.dtl_prod_cd, rtrim(ltrim(b.dtl_prod_desc))"
g_strSQL = g_strSQL & " FROM product_detail_ref b "
g_strSQL = g_strSQL & " ORDER BY rtrim(ltrim(b.dtl_prod_desc)) "
Case Else
Exit Sub
End Select
If p_and_C <> String.Empty Then
g_strSQL = g_strSQL & "'" & String.Empty & "','" & String.Empty & "','" & p_and_C & "'"
End If
If g_strSQL <> "" Then
objcmd.CommandText = g_strSQL
rsProducts = objcmd.ExecuteReader()
End If
'Process results from query
If rsProducts.HasRows = False Then
rsProducts.Close()
Exit Sub
Else
' This nested if will check which radio button is selected and add the corresponding
' 'all' entry to the top of the lstProduct box
If rdbProductPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_P_AND_C)
ElseIf rdbProductNonPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_NON_P_AND_C)
Else
ProductList.Items.Add(PAndCConstants.ALL)
End If
ProductList.SelectedIndex = 0
While rsProducts.Read()
ProductList.Items.Add(rsProducts(0))
End While
ProductList.SetSelected(0, True)
rsProducts.Close()
End If
rsProducts = Nothing
End Sub