I have a form in which there are around 6 multiselect listBoxes. the listBoxes are populated from different tables. I have no problem in storing the selections from listBoxes in variables and then using the variables in a SQL query. the variable stores the selected item from listBox as follows:
If clientList.SelCount > 0 Then
For i = 0 To clientList.ListCount - 1
If clientList.Selected(i) Then
If Len(criteria_cl) = 0 Then
criteria_cl = Chr(39) & clientList.List(i) & Chr(39)
Else
criteria_cl = criteria_cl & "," & Chr(39) & clientList.List(i) & Chr(39)
End If
End If
Next
Else
End If
the SQL query is as follows with more variables which are called criteria_xx
strsql = "select * from pmt_hist_dmart_step2 where dbr_portfolio in (" & criteria_pf & ") and DBR_CLIENT in (" & criteria_cl & _
") and DBR_ACCT_TYPE in (" & criteria_ac & ")..... ;"
How do I deal with a situation when the user makes no selection. Currently, the criteria_xx variable becomes blank and the IN clause contains ('') and throws an error.
Please provide some advice on how to overcome this? If it were only two or three listBoxes, I would written different queries but this is six multiselect listBoxes and I have no clue.
Thanks in advance.
Here's one approach:
strsql = " select * " & _
" from pmt_hist_dmart_step2 " & _
" where " & iif(len(criteria_pf) = 0, _
"", _
"dbr_portfolio in (" & criteria_pf & ") and " _
) & _
iif(len(criteria_cl) = 0, _
"", _
"DBR_CLIENT in (" & criteria_cl & ") and " _
) & _
iif(len(criteria_ac) = 0, _
"", _
"DBR_ACCT_TYPE in (" & criteria_ac & ") and " _
) & _
... & _
" 1 = 1;"
The idea here is that each clause of the form dbr_portfolio in (...) should only be included if the ... is non-blank. iif is a built-in function that takes three arguments; if its first argument is true, then it returns its second argument, and if its first argument is false, then it returns its third argument. For example, iif(1 = 1, 5, 10) returns 5, and iif(1 = 2, 5, 10) returns 10. (N.B. The second and third arguments are both always evaluated, even though one of them is ignored afterward.)
Since something like where and or and and would not be valid SQL, I include each and within the iif-controlled code of the previous clause. Then, since a final and would not be valid SQL, I tacked on a final 1 = 1 clause that has no actual effect.
(By the way, sorry if my indentation scheme is ugly; it's been over a dozen years since I last wrote VB6, so I really don't remember how VB6 code is usually formatted.)
Related
I am trying to update my Table (Referral) Field name (referdate) type Date
to be updated by using inputbox, where the user pass the number through the input box and then to this number to referdate to give me date + 2 days result. (example: inputbox 2 days, add 2 days to 20-12-2020 result is 22-12-2020)
the error I get (syntax error in the update statement)
my access version is 2013
my code below:
Dim S As Integer
S = InputBox(" How many days to follow", "Number of Days !")
DoCmd.RunSQL "UPDATE Referral" & _
"SET referdate = referdate" & Me.referdate + S & _
"where SRSno = " & Me.SRSno
Me.Refresh
According to the docs (https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/update-statement-microsoft-access-sql), it seems that your statement might be including the existing column value being concatenated with the local variable.. Try this:
DoCmd.RunSQL "UPDATE Referral" & _
"SET referdate = " & Me.referdate + S & _
"where SRSno = " & Me.SRSno
The difference is subtle, but the Microsoft example shows adding a value as part of the query expression to the existing column value:
SET OrderAmount = OrderAmount * 1.1,
The alternative syntax for your case might be:
DoCmd.RunSQL "UPDATE Referral" & _
"SET referdate = referdate + " & S & _
"where SRSno = " & Me.SRSno
In either case, notice that referdate only appears once in the statement.
Include DateAdd and don't forget the spaces:
If Val(S) > 0 Then
DoCmd.RunSQL "UPDATE Referral " & _
"SET referdate = DateAdd('d', " & Val(S) & ", referdata) " & _
"WHERE SRSno = " & Me.SRSno & ""
End If
Getting this error out of an old VB6 app that I've been presented with updating. So I got XP Mode up and running and VB6 installed and updated on it and I've added the menu option that was requested of me, but now I'm getting this error.
There are several examples of this error or similar here on SO and I looked through a bunch of them, but the circumstances aren't exactly the same and I'm still a pretty newbie developer and I just need help. I tested the query I wrote on our dev server and the VB syntax around it, that part is working fine. I think it has something to do with the result set logic near the end:
Private Sub FillDoor()
Dim m_rsDoor As ADODB.Recordset
cboDoorStyle.Clear
Set m_rsDoor = conSQL.Execute("SELECT bpm.[Description] " & _
"FROM tblBrandProductMaster bpm " & _
"INNER JOIN tblDoorStyles ds " & _
"ON ds.DoorStyleCode = bpm.Code " & _
"INNER JOIN tblFamilyDoorStyles fds " & _
"ON bpm.Code = fds.DoorStyleCode " & _
"INNER JOIN tblFamilyLines fl " & _
"ON fds.FamilyLineCode = fl.FamilyLineCode " & _
"WHERE fl.FamilyLineCode = '" & strFamID & "' " & _
"AND ds.DFFactive = 1 " & _
"ORDER BY bpm.[Description] ASC")
Do While Not m_rsDoor.EOF
cboDoorStyle.AddItem m_rsDoor!Description
m_rsDoor.MoveNext
Loop
Set m_rsDoor = Nothing
End Sub
****Edit: I'm using that query to populate a particular drop-down in the app and it is working on both on the SQL server and in the app.
Some of the examples on here use an If loop instead of a Do While Not, but they both get the same thing done and I don't think that's the issue. I also don't think that's the issue because I copied and pasted that part from another menu option on the app and that option works when I click it. It only throws the error when I choose the option I added.
Thanks, I appreciate any help anyone can offer.
Modify like below code:
Private Sub FillDoor()
Dim m_rsDoor As ADODB.Recordset
Set m_rsDoor = New Recordset
Dim ActiveConnection as String
ActiveConnection = "XXXXXXXXXXX"
Dim strSQL as String
strSQL = "SELECT bpm.[Description] " & _
"FROM tblBrandProductMaster bpm " & _
"INNER JOIN tblDoorStyles ds " & _
"ON ds.DoorStyleCode = bpm.Code " & _
"INNER JOIN tblFamilyDoorStyles fds " & _
"ON bpm.Code = fds.DoorStyleCode " & _
"INNER JOIN tblFamilyLines fl " & _
"ON fds.FamilyLineCode = fl.FamilyLineCode " & _
"WHERE fl.FamilyLineCode = '" & strFamID & "' " & _
"AND ds.DFFactive = 1" & _
"ORDER BY bpm.[Description] ASC"
m_rsDoor.open strSQL, ActiveConnection, adOpenStatic, adLockOptimistic
Do While Not m_rsDoor.EOF
cboDoorStyle.AddItem m_rsDoor!Description
m_rsDoor.MoveNext
Loop
Set m_rsDoor = Nothing
End Sub
This error comes when there are no record in the record set. Please check if your query is correct and giving records.
I'm trying to get the datareport working since dataflexgrid is already working, although I'm having a hard time passing the values to datareport, I can't even pass one please help thanks.
PS. all of them are in one form
Set mRS = New ADODB.Recordset
mRS.CursorLocation = adUseClient
mRS.CursorType = adOpenForwardOnly
mRS.LockType = adLockReadOnly
If mRS.State = 1 Then mRS.Close
mRS.Open "SHAPE {" & _
"SELECT " & _
"space(memberstree.level*6) + customer.description, " & _
"customer.customercode, " & _
"customer.remarks, " & _
"customer.membersince " & _
"From CUSTOMER " & _
"INNER JOIN memberstree on customer.customercode = memberstree.customercode " & xRootNode & " " & _
"ORDER by memberstree.pedigree + ltrim(str(memberstree.node,6,0))} AS rsCustomer " & _
"APPEND (( SHAPE {SELECT transactionNo, logdate, customercode, GrandTotal " & _
"From FinishedTransaction where " & xCriteria & "} AS rsTransaction " & _
"APPEND ({SELECT TransactionNo, Description, Qty From FinishedSales} As rsSales " & _
"RELATE TransactionNo TO TransactionNo))" & _
" RELATE customercode TO customercode)", gCNMark
mRS.Requery
Set MSHFlexGrid1.DataSource = mRS
I think this is the code that isn't working
With rptShape
Set .DataSource = mRS
.DataMember = ""
With .Sections("FinishedSales_Detail").Controls
.Item("txtDescription").DataMember = "rsSales"
.Item("txtDescription").DataField = "Description"
End With
.Show 1
It's ok now I have 3 TABLE with 2 SHAPE Command but in the data report I have 3 Group Header and supposed to be 2 as well.
strCode = "Private Sub AcclvsTime() " & vbCr _
& "Set myChtObj = oExcelWriteWorkSheet.ChartObjects.Add(100,375,75,225) "& vbCr _
& "myChtObj.Chart.ChartType = 4 " & vbCr _
& "myChtObj.Chart.SetSourceData objWriteWorkbook.Sheets("sheet2").Range("A1:B15")" & vbCr _
& "End Sub"
objWriteExcel.VBE.ActiveVBProject.VBComponents.Item("Sheet1").CodeModule.AddFromString(strCode)
When I executed this code i got the error “end of the statement expected in line 4” (& "myChtObj.Chart.SetSourceData objWriteWorkbook.Sheets("sheet2").Range("A1:B15")" & vbCr _)
Can any one help me where is the mistake?
#paxdiablo: I would comment, but don't see a comment button.
Notice, though, the second quote from Range("A1:B15")" & vbCr is started from "myChtObj.Chart.SetSourceData
Having the full block of code would help better, as we can't tell what kind of end statement you will need. I.e, your "End Sub" is in double quotes. If that's the end of the sub, you need to take them out.
Building strings by concatenation is cumbersome and errorprone. Especially, if the result is a multiline string, use Join:
strCode = Join( Array( _
"Private Sub AcclvsTime()" _
, " Set myChtObj = oExcelWriteWorkSheet.ChartObjects.Add(100,375,75,225)" _
, " myChtObj.Chart.ChartType = 4" _
, " myChtObj.Chart.SetSourceData objWriteWorkbook.Sheets(""sheet2"").Range(""A1:B15"")" _
, "End Sub" _
), vbCrLf)
WScript.Echo strCode
output:
Private Sub AcclvsTime()
Set myChtObj = oExcelWriteWorkSheet.ChartObjects.Add(100,375,75,225)
myChtObj.Chart.ChartType = 4
myChtObj.Chart.SetSourceData objWriteWorkbook.Sheets("sheet2").Range("A1:B15")
End Sub
to reduce the noise caused by & and the repeating stuff vbCr(Lf). That will improve your chances to see the problems/mistakes. (Exactly two literals - "sheet2", "A1:B15" - to quote).
Addional Remark:
Given that the culprit is:
"whatever("sheet2").Range("A1:B15")"
it is obvious, that remedy
"whatever(""sheet2"").Range(""A1:B15"")"
is easier to read/check/write and less errorprone than
"whatever(" & Chr(24) & "sheet2" & Crh(34) & ").Range(" & Chr(34) + "A1:B15" & Chr(32) & ")"
Avoiding "" in literals by splicing in & Chr(34) &s is a bad strategy.
" ... Range("A1:B15")" & vbCr
Note those quotes within quotes on your fourth line (for both "sheet2" and "A1:B15") - you need to fix that.
If you want to put quotes within quotes, you can do it thus, by escaping. Two consecutive " characters within a double-quoted string will be translated to a single ".
"the word ""xyzzy"" is quoted"
Alternatively, you can also use chr(34) to get the quote:
"the word " & chr(34) & "xyzzy" & chr(34) & " is quoted"
This may be preferable in more complex cases, though I've rarely had a need for it.
I have a routine which reads one recordset, and adds/updates rows in a similar recordset. The routine starts off by copying the columns to a new recordset:
Here's the code for creating the new recordset..
For X = 1 To aRS.Fields.Count
mRS.Fields.Append aRS.Fields(X - 1).Name, aRS.Fields(X - 1).Type, aRS.Fields(X - _
1).DefinedSize, aRS.Fields(X - 1).Attributes
Next X
Pretty straight forward. Notice the copying of the name, Type, DefinedSize & Attributes...
Further down in the code, (and there's nothing that modifies any of the columns between.. ) I'm copying the values of a row to a row in the new recordset as such:
For C = 1 To aRS.Fields.Count
mRS.Fields(C - 1) = aRS.Fields(C - 1)
Next C
When it gets to the last column which is a numeric, it craps with the "Mutliple-Step Operation Generated an error" message.
I know that MS says this is an error generated by the provider, which in this case is ADO 2.8. There is no open connect to the DB at this point in time either.
I'm pulling what little hair I have left over this one... (and I don't really care at this point that the column index is 'X' in one loop & 'C' in the other... I'll change it later when I get the real problem fixed...)
You have to set Precision and NumericScale for adDecimal and adNumeric fields before opening synthetic recordset like this
For X = 1 To aRS.Fields.Count
With aRS.Fields(X - 1)
Select Case .Type
Case adChar, adWChar, adBinary, _
adVarChar, adVarWChar, adVarBinary, _
adLongVarChar, adLongVarWChar, adLongVarBinary
mRS.Fields.Append .Name, .Type, .DefinedSize, .Attributes
Case adDecimal, adNumeric
mRS.Fields.Append .Name, .Type, , .Attributes
mRS.Fields(mRS.Fields.Count - 1).Precision = .Precision
mRS.Fields(mRS.Fields.Count - 1).NumericScale = .NumericScale
Case Else
mRS.Fields.Append .Name, .Type, , .Attributes
End Select
End With
Next
FYI: you might be get a recordset with a field that has no name from the database e.g.
SELECT 5, 'No name'
but ADO will not allow an empty name on Append method. You might also get a recordset with duplicate fields from the database e.g.
SELECT 5 AS Col, 'Second' AS Col
which in your case will bomb out on Append too.
Guess 2 : the correct line should be
mRS.Fields(C - 1).value = aRS.Fields(C - 1).value
My guess is you have have a null and you are not treating the dbnull type right.
Please see my comments about finding an alternative approach but the straight answer is the Field objects' Precision and NumericScale properties need to be set. Here's a repro of your error, uncomment the two lines to fix the error:
Sub bfgosdb()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE Test1 " & vbCr & "(" & vbCr & " col1 VARCHAR(255)," & _
" " & vbCr & " col2 INTEGER, " & vbCr & " col3 DECIMAL(19,4)" & vbCr & ");"
.Execute Sql
Sql = _
"INSERT INTO Test1 (col1, col2, col3) " & vbCr & "VALUES" & _
" (" & vbCr & "'128000 and some change', " & vbCr & "128000, " & vbCr & "128000.1234" & vbCr & ");"
.Execute Sql
Sql = _
"INSERT INTO Test1 (col1, col2, col3) " & vbCr & "VALUES" & _
" (" & vbCr & "NULL, " & vbCr & "NULL, " & vbCr & "NULL " & vbCr & ");"
.Execute Sql
Sql = _
"SELECT T11.col1, T11.col2, T11.col3 " & vbCr & " FROM" & _
" Test1 AS T11;"
Dim aRS
Set aRS = .Execute(Sql)
Dim mRS
Set mRS = CreateObject("ADODB.Recordset")
Dim X As Long
For X = 1 To aRS.Fields.Count
mRS.Fields.Append aRS.Fields(X - 1).Name, aRS.Fields(X - 1).Type, aRS.Fields(X - _
1).DefinedSize, aRS.Fields(X - 1).Attributes
' mRS.Fields(mRS.Fields.Count - 1).NumericScale = aRS.Fields(X - 1).NumericScale '
' mRS.Fields(mRS.Fields.Count - 1).Precision = aRS.Fields(X - 1).Precision '
Next X
mRS.Open
Do While Not aRS.EOF
mRS.AddNew
Dim C As Long
For C = 1 To aRS.Fields.Count
mRS.Fields(C - 1) = aRS.Fields(C - 1)
Next C
aRS.MoveNext
Loop
End With
Set .ActiveConnection = Nothing
End With
End Sub