Displays the result many times in Mulitselect Listbox Search in VB6 - sql

I am creating a program in vb6 with ms access. while i am searching the database from multi select list box in vb it displays the results wrongly.
if i click the first item it shows one time
if i click second item it shows that item two times
it i click third item it shows that item three times.
how to solve this
i tried the below code
For i = List1.ListCount - 1 To 0 Step -1
If List1.Selected(i) = True Then
If str <> "" Then str = str & ""
If Val(List1.SelCount) = 1 Then
str = List1.List(List1.ListIndex)
Else
str = str & " or name= " & List1.List(List1.ListIndex)
End If
End If
Next i
If str <> "" Then
Set rs = db.OpenRecordset("select * from Customers where name= '" & str & "'")
display
End If
result
Kumar vasanth vasanth kannan kannan kannan

Try this:
Option Explicit
Private Sub Command1_Click()
Dim i As Integer
Dim str As String
For i = List1.ListCount - 1 To 0 Step -1
If List1.Selected(i) Then str = str & " or name = '" & List1.List(i) & "'"
Next i
str = Mid(str, 4)
If str <> "" Then
Set rs = db.OpenRecordset("select * from Customers where " & str)
display
End If
End Sub

Related

Is ther a Join function in vba to combine multiple fields rather than using concatenate function in access?

Thank you to all your responses.
I have a table with one id field and R1-R30 fields.
I was able to concatenate R1-R30 fields in a query using
Route: Trim([R1] & IIf([R2]="",""," ") & [R2] & IIf([R3]="",""," ") & [R3] & IIf([R4]="",""," ") & [R4] & IIf([R5]="",""," ") & [R5] & IIf([R6]="",""," ") & [R6] & IIf([R7]="",""," ") & [R7] & IIf([R8]="",""," ") & [R8] & IIf([R9]="",""," ") & [R9] & IIf([R10]="",""," ") & [R10] & IIf([R11]="",""," ") & [R11] & IIf([R12]="",""," ") & [R12] & IIf([R13]="",""," ") & [R13] & IIf([R14]="",""," ") & [R14] & IIf([R15]="",""," ") & [R15] & IIf([R16]="",""," ") & [R16] & IIf([R17]="",""," ") & [R17] & IIf([R18]="",""," ") & [R18] & IIf([R19]="",""," ") & [R19] & IIf([R20]="",""," ") & [R20] & IIf([R21]="",""," ") & [R21] & IIf([R22]="",""," ") & [R22] & IIf([R23]="",""," ") & [R23] & IIf([R24]="",""," ") & [R24] & IIf([R25]="",""," ") & [R25] & IIf([R26]="",""," ") & [R26] & IIf([R27]="",""," ") & [R27] & IIf([R28]="",""," ") & [R28] & IIf([R29]="",""," ") & [R29] & IIf([R30]="",""," ") & [R30])
My question is if the Join function I found can be applied to a query where the delimeter could be a spare, comma or slash.
Join (source_array,[delimiter])
Thanks
This would be the code to take all values of 1 single recordset into a bidimensional array, and then take those values into a unidimensional array (excluding null values, because null values cannot be joined with JOIN).
I think it would be better just looping trough every field with the loop, but in case it might help, i'll post it.
To replicate your issue, I just created a database with 1 single table with 2 records:
I'll concatenate all fields, excluding ID field. So with an easy query, I can get a recordset of 1 single record, using ID field as parameter:
SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4
FROM Tabla1
WHERE (((Tabla1.Id)=1));
And then the VBA code to Msgbox the fields joined, using a comma as delimiter.
Sub JOIN_RST()
Dim rst As Recordset
Dim vArray As Variant
Dim SingleArray() As Variant
Dim i As Long
Dim MySQL As String
Dim STRJoined As String
MySQL = "SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4 " & _
"FROM Tabla1 WHERE (((Tabla1.Id)=2));" 'query to get a single recordset.
Set rst = Application.CurrentDb.OpenRecordset(MySQL, 2, 4)
DoEvents
If rst.RecordCount > 0 Then
rst.MoveLast
rst.MoveFirst
vArray = rst.GetRows
ReDim SingleArray(UBound(vArray))
For i = 0 To UBound(SingleArray)
If IsNull(vArray(i, 0)) = True Then
SingleArray(i) = ""
Else
SingleArray(i) = vArray(i, 0)
End If
Next i
Debug.Print vArray(0, 0) 'Field 1
Debug.Print vArray(1, 0) 'Field 2
Debug.Print vArray(2, 0) 'Field 3
Debug.Print vArray(3, 0) 'Field 4
STRJoined = Join(SingleArray, ",")
Debug.Print STRJoined
End If
Set rst = Nothing
Erase vArray
Erase SingleArray
DoEvents
End Sub
If I execute this code using as WHERE parameter ID=1 , in debugger Window I get:
First Record
1
Null
My first record. Got a null value in Field 3 (it's empty)
First Record,1,,My first record. Got a null value in Field 3 (it's empty)
With ID=2 I get:
Second Record
2
Not null
Second Record
Second Record,2,Not null,Second Record
So this kinda works. I hope you can adapt it to your needs. but as i said. looking at the code, I think it would be easier just looping trough fields in a single query with all records. something like this:
Sub LOOPING_TROUGHT_FIELDS()
Dim RST As Recordset
Dim Joined_Records() As Variant
Dim i As Long
Dim MySQL As String
Dim STRJoined As String
Dim FLD As Field
MySQL = "SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4 " & _
"FROM Tabla1;" 'query to get all recordset you want to join
Set RST = Application.CurrentDb.OpenRecordset(MySQL, 2, 4)
DoEvents
If RST.RecordCount > 0 Then
RST.MoveLast
RST.MoveFirst
i = 0
ReDim Joined_Records(RST.RecordCount)
Do Until RST.EOF = True
For Each FLD In RST.Fields
If IsNull(FLD.Value) = True Then
STRJoined = STRJoined & "" & ","
Else
STRJoined = STRJoined & FLD.Value & ","
End If
Next FLD
Joined_Records(i) = Left(STRJoined, Len(STRJoined) - 1) 'we get 1 minus because there is an extra comma at end
i = i + 1
STRJoined = ""
RST.MoveNext
Loop
End If
Set RST = Nothing
Set FLD = Nothing
For i = 0 To UBound(Joined_Records) Step 1
Debug.Print Joined_Records(i)
Next i
Erase Joined_Records
End Sub
I don't know how many records you got. Try both and check how long does each option takes, and then choose 1.
Hope you can adapt all this to your needs. Welcome to SO.

BC30420 'Sub Main' was not found error in a Windows Form app

I've created a Windows Form application. It is my understanding that you do not have to have a Sub Main() in a Windows Form app. However I'm getting this error when I build my project:
BC30420 'Sub Main' was not found in 'LoanCalculator.Module1'.
First of all I don't know why it's saying 'LoanCalculator.Module1'. Both my form and my class are named LoanCalculator.vb. When I started the project I started writing the code in the original module. Then I added a module, named it 'LoanCalculator' and moved what code I had written to that module and finished it there. I deleted the original module. Now it builds fine with the exception of this one error. Here's my code:
Imports System.Windows.Forms
Public Class LoanCalculator
Private Sub Calculate()
Dim str As String
Dim intLoanAmt As Integer
Dim intDown As Integer
Dim intFees As Integer
Dim intBalance As Integer
Dim dblIntsRate As Single
Dim intLoanTerm As Integer
Dim sngInterestPaid As Single
Dim intTermMonths As Integer
Dim dblMonthlyPmt As Integer
Dim intTotalPaid As Integer
Dim dblYon As Double
Dim dblXon As Double
Dim dblZon As Double
If Not CheckInput() Then
Return
End If
intLoanAmt = Convert.ToInt32(txtLoan.Text)
intFees = Convert.ToInt32(txtFees.Text)
intDown = Convert.ToInt32(txtDown.Text)
intBalance = Convert.ToInt32(intLoanAmt - intDown + intFees)
intLoanTerm = Convert.ToInt32(txtTerm.Text)
dblIntsRate = Convert.ToDouble(txtTerm.Text)
intTermMonths = intLoanTerm * 12
dblYon = dblIntsRate / 1200
dblXon = dblYon + 1
dblZon = Math.Pow(dblXon, intTermMonths) - 1
dblMonthlyPmt = (dblYon + (dblYon / dblZon)) * intBalance
intTotalPaid = dblMonthlyPmt * intTermMonths
sngInterestPaid = intTotalPaid - intBalance
str = "Loan balance =" & Space(11) & intBalance.ToString & vbCrLf
str = str & "Loan Term =" & Space(16) & intLoanTerm.ToString & " years" & vbCrLf
str = str & "Interest paid =" & Space(17) & intTotalPaid.ToString & vbCrLf
str = str & "Monthly payment =" & Space(5) & dblMonthlyPmt.ToString
lblResults.Text = str
End Sub
Private Function CheckInput() As Boolean
Dim strErr As String = ""
If txtLoan.Text.Length = 0 Then
strErr = "Enter loan amount" & vbCrLf
End If
If txtDown.Text.Length = 0 Then
strErr = strErr & "Enter down payment" & vbCrLf
End If
If txtInterest.Text.Length = 0 Then
strErr = strErr & "Enter interest rate" & vbCrLf
End If
If txtFees.Text.Length = 0 Then
strErr = strErr & "Enter fees" & vbCrLf
End If
If txtTerm.Text.Length = 0 Then
strErr = strErr & "Enter loan term" & vbCrLf
End If
If strErr.Length > 0 Then
MessageBox.Show(strErr)
Return False
Else
Return True
End If
End Function
End Class
How can I fix this?

VBA: Error 3265 - "Item not found in this collection"

In Access 2016 I'm trying to open a recordset and save data from it in other variables, but I keep getting this error.
The program itself has more parts, but I only get error in this one, it just update data on its database.
This is my code:
Option Compare Database
Option Explicit
Private Sub btnValidateTimesheet_Click()
' Update timesheet to "Justificat"
Dim intIdTimesheet As Integer
If IsNull(cmbDraftTimesheets.Value) Then
MsgBox("You have to select a timesheet that is Borrador")
Exit Sub
End If
intIdTimesheet = cmbDraftTimesheets.Column(0)
DoCmd.SetWarnings False
DoCmd.RunSQL "update Timesheets set estat = ""Justificat"" where id=" & intIdTimesheet
DoCmd.SetWarnings True
End Sub
Private Sub btnValidateTimesheetLines_Click()
' We select the timesheet_lines for employee, project, activity and dates selected
' For each justification, a new "Justificat" Timesheet is generated which hang timesheet_lines
' ------------------------------- Variables -------------------------------
Dim dictTsLines As Object
Set dictTsLines = CreateObject("Scripting.Dictionary")
' Form inputs
Dim intCodTreb As Integer
Dim strCodProj As String
Dim dateInici, dateFi As Date
Dim intExercici As Integer
' Query strings
Dim strSQLFrom, strSQLWhere As String
Dim strSQLCount, strSQLJustAct, strSQLTsLines As String
' Recordsets
Dim rsCount, rsJustAct, rsTimesheets, rsTsLines As Recordset
' Aux and others...
Dim continue As Integer
Dim intIdJustificacio, intIdTs As Integer
Dim strActivitat As String
' --------------------------------------- Main ---------------------------------------------
' Taking form data
intCodTreb = cmbTreballador.Column(0)
strCodProj = cmbProjecte.Column(1)
dateInici = txtDataInici.Value
dateFi = txtDataFi.Value
' We check the dates are correct
If IsNull(dateInici) Or IsNull(dateFi) Then
MsgBox("Dates can't be null")
Exit Sub
End If
If dateFi < dateInici Then
MsgBox("Start date must be earlier or the same as final date")
Exit Sub
End If
If year(dateInici) <> year(dateFi) Then
MsgBox("Dates must be in the same year")
Exit Sub
End If
intExercici = year(dateInici)
' Make of the clause FROM and WHERE of the select query of timesheet_lines
strSQLFrom = " from (timesheet_lines tsl " & _
" left join timesheets ts on tsl.timesheet_id = ts.id) " & _
" left join justificacions j on j.id = ts.id_justificacio "
strSQLWhere = " where ts.estat = ""Borrador"" " & _
" and tsl.data >= #" & Format(dateInici, "yyyy/mm/dd") & "# " & _
" and tsl.data <= #" & Format(dateFi, "yyyy/mm/dd") & "# "
If Not IsNull(intCodTreb) Then
strSQLWhere = strSQLWhere & " and tsl.cod_treb = " & intCodTreb
End If
If Not IsNull(strCodProj) Then
strSQLWhere = strSQLWhere & " and j.cod_proj=""" & strCodProj & """ "
End If
' Alert how much timesheet_lines are going to be validated
strSQLCount = "select count(*) " & strSQLFrom & strSQLWhere
Set rsCount = CurrentDb.OpenRecordset(strSQLCount)
Continue Do = MsgBox( rsCount(0) & " registries are going to be validated" & vbNewLine & _
"Do you want to continue?", vbOKCancel)
If continue <> 1 Then
Exit Sub
End If
' We select the tuples Justificacio, Activitat of timesheet_lines selected
strSQLJustAct = "select distinct ts.id_justificacio " & strSQLFrom & strSQLWhere
Set rsJustAct = CurrentDb.OpenRecordset(strSQLJustAct)
Set rsTimesheets = CurrentDb.OpenRecordset("Timesheets")
' A new timesheet is generated for each tupla
Do While Not rsJustAct.EOF
intIdJustificacio = rsJustAct(0)
strActivitat = rsJustAct(1)
rsTimesheets.AddNew
rsTimesheets!data_generacio = Now()
rsTimesheets!estat = "Justificat"
rsTimesheets!Id_justificacio = intIdJustificacio
rsTimesheets!activitat = strActivitat
rsTimesheets!data_inici = dateInici
rsTimesheets!data_fi = dateFi
rsTimesheets!exercici = intExercici
intIdTs = rsTimesheets!Id
rsTimesheets.Update
' We save the related id of the selected timesheet in a dictionary
dictTsLines.Add intIdJustificacio & "_" & strActivitat, intIdTs
rsJustAct.MoveNext
Loop
' We select all the affected timesheet_lines and we update the related timesheet using the dictionary
strSQLTsLines = "select tsl.id, tsl.timesheet_id, ts.id_justificacio, ts.activitat " & strSQLFrom & strSQLWhere
Set rsTsLines = CurrentDb.OpenRecordset(strSQLTsLines)
With rsTsLines
Do While Not .EOF
.EDIT
intIdJustificacio = !Id_justificacio
strActivitat = !activitat
!timesheet_id = dictTsLines.Item(intIdJustificacio & "_" & strActivitat)
.Update
.MoveNext
Loop
End With
rsTimesheets.Close
Set rsCount = Nothing
Set rsJustAct = Nothing
Set rsTimesheets = Nothing
Set rsTsLines = Nothing
End Sub
Debugger: The error is coming up at the line:
strActivitat = rsJustAct(1)
I checked that the data the recordset is saving exists and it does.
Your recordset contains just one column ("select distinct ts.id_justificacio"), but you are trying to read second column strActivitat = rsJustAct(1)
Add requred column to recordset.

"system resource exceeded" when running a function

I have a field called "sku" which uniquely identifies products on the table, there are about 38k products. I have a "sku generator" which uses other fields in the table to create the SKU. It's worked perfectly without an issue until I started producing SKUs for a large amount of products. I would launch the generator and it would stop around 15,000 and say "System Resource exceeded" and highlight the following code in the function:
Found = IsNull(DLookup("sku", "Loadsheet", "[sku]='" & TempSKU & "'"))
I didn't have time to fully fix the issue, so a temporary fix for me was to split the database in two, and run the sku generator seperately on both files. Now that I have more time I want to investigate why exactly it gets stuck around this number, and if there's a possibility of fixing this issue (it would save some time with splitting files and then grouping them again). I also have an issue with it getting really slow at times, but I think it's because it's processing so much when it runs. Here is the function
Option Compare Database
Private Sub Command2_Click() 'Generate SKU
Command2.Enabled = False: Command3.Enabled = False: Command2.Caption = "Generating ..."
Me.RecordSource = ""
CurrentDb.QueryDefs("ResetSKU").Execute
Me.RecordSource = "loadsheet_4"
Dim rs As Recordset, i As Long
Set rs = Me.Recordset
rs.MoveLast: rs.MoveFirst
For i = 0 To rs.RecordCount - 1
rs.AbsolutePosition = i
rs.Edit
rs.Fields("sku") = SetSKU(rs)
rs.Update
DoEvents
Next
Command2.Enabled = True: Command3.Enabled = True: Command2.Caption = "Generate SKU"
End Sub
Public Function SetSKU(rs As Recordset) As String
Dim TempStr As String, TempSKU As String, id As Integer, Found As Boolean, ColorFound As Variant
id = 1: ColorFound = DLookup("Abbreviated", "ProductColors", "[Color]='" & rs.Fields("single_color_name") & "'")
TempStr = "ORL-" & UCase(Left(rs.Fields("make"), 2)) & "-"
TempStr = TempStr & Get1stLetters(rs.Fields("model"), True) & rs.Fields("year_dash") & "-L-"
TempStr = TempStr & "WR-"
TempStr = TempStr & IIf(IsNull(ColorFound), "?", ColorFound) & "-4215-2-"
TempStr = TempStr & rs.Fields("color_code")
TempSKU = Replace(TempStr, "-L-", "-" & ADDZeros(id, 2) & "-L-")
Found = IsNull(DLookup("sku", "Loadsheet", "[sku]='" & TempSKU & "'"))
While Found = False
id = id + 1
TempSKU = Replace(TempStr, "-L-", "-" & ADDZeros(id, 2) & "-L-")
Found = IsNull(DLookup("sku", "Loadsheet", "[sku]='" & TempSKU & "'"))
Wend
If id > 1 Then
' MsgBox TempSKU
End If
SetSKU = TempSKU
End Function
Public Function Get1stLetters(Mystr As String, Optional twoLetters As Boolean = False) As String
Dim i As Integer
Get1stLetters = ""
For i = 0 To UBound(Split(Mystr, " ")) 'ubound gets the number of the elements
If i = 0 And twoLetters Then
Get1stLetters = Get1stLetters & UCase(Left(Split(Mystr, " ")(i), 2))
GoTo continueFor
End If
Get1stLetters = Get1stLetters & UCase(Left(Split(Mystr, " ")(i), 1))
continueFor:
Next
End Function
Public Function ADDZeros(N As Integer, MAX As Integer) As String
Dim NL As Integer
NL = Len(CStr(N))
If NL < MAX Then
ADDZeros = "0" & N 'StrDup(MAX - NL, "0") & N
Else: ADDZeros = N
End If
End Function
Notes: This function also calls other functions as well that adds a unique identifier to the SKU and also outputs the first letter of each word of the product
Also I'm running on 64 bit access.
If you require any other info let me know, I didn't post the other functions but if needed let me know.
thanks.
I am not 100% sure how you have split the Database into two files and that you are running the generator on both files. However I have a few suggestion to the function you are using.
I would not pass the recordset object to this function. I would rather pass the ID or unique identifier, and generate the recordset in the function. This could be a good start for efficiency.
Next, declare all objects explicitly, to avoid library ambiguity. rs As DAO.Recordset. Try to make use of inbuilt functions, like Nz().
Could Get1stLetters method be replaced with a simple Left() function? How about ADDZeros method?
Using DLookup might be a bit messy, how about a DCount instead? Could the following be any use now?
Public Function SetSKU(unqID As Long) As String
Dim TempStr As String, TempSKU As String
Dim id As Integer
Dim ColorFound As String
Dim rs As DAO.Recordset
id = 1
Set rs = CurrentDB.OpenRecordset("SELECT single_color_name, make, model, year_dash, color_code " & _
"FROM yourTableName WHERE uniqueColumn = " & unqID)
ColorFound = Nz(DLookup("Abbreviated", "ProductColors", "[Color]='" & rs.Fields("single_color_name") & "'"), "?")
TempStr = "ORL-" & UCase(Left(rs.Fields("make"), 2)) & "-"
TempStr = TempStr & Get1stLetters(rs.Fields("model"), True) & rs.Fields("year_dash") & "-L-"
TempStr = TempStr & "WR-"
TempStr = TempStr & ColorFound & "-4215-2-"
TempStr = TempStr & rs.Fields("color_code")
TempSKU = Replace(TempStr, "-L-", "-" & ADDZeros(id, 2) & "-L-")
While DCount("*", "Loadsheet", "[sku]='" & TempSKU & "'") <> 0
id = id + 1
TempSKU = Replace(TempStr, "-L-", "-" & ADDZeros(id, 2) & "-L-")
Wend
If id > 1 Then
'MsgBox TempSKU'
End If
Set rs = Nothing
SetSKU = TempSKU
End Function

Search between two dates w/ datarows in vb 2010

I am trying to search between two dates in a bound source (SQL table) in VB 2010, using data rows. Since 'between' in unsupported with the data rows function, I used < and >.
So I run this code and the output is 900+ entries when the actual number of entries is 8. After hitting my button a second time without changing anything, the correct number of entries appears.
Private Sub cmdSearch_Click(sender As System.Object, e As System.EventArgs) _
Handles cmdSearch.Click
Dim Expression As String
Dim OrderStr As String = "Area"
Dim DateStr As String
Dim StartDate As String
Dim EndDate As String
Dim Shift As String = ""
Dim Area As String = ""
Dim Product As String
If (DtpStartDate.Value = Nothing Or DtpEndDate.Value = Nothing) Then
MsgBox("Please input a start and end date.")
Exit Sub
End If
If (radShiftAllSearch.Checked <> True _
And radShiftOneSearch.Checked <> True
And radShiftTwoSearch.Checked <> True _
And radShiftThreeSearch.Checked <> True) Then
MsgBox("Please select a shift to search for.")
Exit Sub
End If
Select Case True
Case radShiftOneSearch.Checked
Shift = " AND [Shift] = '1'"
Case radShiftTwoSearch.Checked
Shift = " AND [Shift] = '2'"
Case radShiftThreeSearch.Checked
Shift = " AND [Shift] = '3'"
Case radShiftAllSearch.Checked
Shift = " AND ([Shift] = '1' OR [Shift] = '2' OR [Shift] = '3')"
End Select
**StartDate = DtpStartDate.Value.Subtract(oneday)
EndDate = DtpEndDate.Value.Add(oneday)
'StartDate = Format(DtpStartDate.Value.Subtract(oneday), "M/dd/yyyy")
'EndDate = Format(DtpEndDate.Value.Add(oneday), "M/dd/yyyy")
DateStr = "[Dates] > '" & StartDate & "' AND [Dates] < '" & EndDate & "'"**
If (txtProductSearch.Text = "") Then
Product = ""
Else
Product = "AND [Product] LIKE '" & txtProductSearch.Text & "'"
End If
For h As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(h), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
If (Area = "") Then
Area = Area & " AND ([Area] LIKE '" & XDisplayMember & "'"
Else
Area = Area & " OR [Area] LIKE '" & XDisplayMember & "'"
End If
Next
If (Area <> "") Then
Area = Area & ")"
End If
Expression = DateStr & Product & Shift & Area
TextBox4.Text = Expression
Dim SearchRows() As DataRow = _
ProductionDataSet.Tables("Production_Daily").Select(Expression, OrderStr)
'foundcount = SearchRows.Count - 1
DataGridView1.DataSource = SearchRows
DataGridView1.Show()
End Sub
Thanks