Access Continuos Subform Repeating Information - ms-access

Access Database Form1 is a Continuous Form that has an EmployeeID field you can double click to take you to another form that contains information about the Employee. In order to retain the correct employee I use this code...
Private Sub EmployeeID_DblClick(cancel as integer)
Dim myID as variant
myID = me.EmployeeID
DoCmd.OpenForm "frm_EmployeeInfo",,,,,,myID
End Sub
This Not only brings up the correct employee information but populates the number into a hidden textbox to retain the information.
On the Employee Form there is a TabControl with 4 tabs, one of the tabs contains a Continous subform that I am trying to populate employee information but instead of the information being populated down (let's say Employee X has 8 lines of different attributes to display) it is repeating the same one. Here is my code for the subform:
Option Compare Database
Private Sub Form_open(cancel As Integer)
Dim strConnection, strSQL As String
Dim conn As ADODB.Connection
Dim tbl As ADODB.Recordset
Dim SourceCode As String
Dim myID As Variant
Set conn = New ADODB.Connection
strConnection = "ODBC;Driver={SQLserver};DSN=AccessDatabase;Server=Labor;DATABASE=Source;Trusted_Connection=Yes;"
conn.Open strConnection
myID = CInt(Me.OpenArgs)
SourceCode= Nz(DLookup("[SourceCode]", "Locaton", "[LOC_ID] = Forms!frmUtility![Site].value"), "")
If SourceCode<> "" Then
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & SourceCode & "_EmployeesBenefitsNew WHERE EmployeeID= " & myID
Else
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & "EmployeesBenefitsNew WHERE EmployeeID= " & myID
End If
Set tbl = New ADODB.Recordset
With tbl
Set .ActiveConnection = conn
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
With tbl
On Error Resume Next
.MoveFirst
Do Until tbl.EOF
Me.txtBenefitID.Value = tbl!BenefitID
Me.txtDeductionAmt.Value = tbl!DeductionAmount
Me.txtBenefitAmt.Value = tbl!BenefitAmount
Me.txtCoverageAmt.Value = tbl!CoverageAmount
Me.txtEffDt.Value = tbl!EffectiveDate
Me.txtTermDt.Value = tbl!ExpirationDate
Set Me.Recordset = tbl
.MoveNext
Loop
.Close
End With
conn.Close
Set conn = Nothing
Set tbl = Nothing
End Sub
Can anyone shed some light on this situation? Thanks!

You need to either set the recordset or the recordsource with the data, you cannot write to a continuous form on different lines, the lines only display as different if you have a recordset.
So
''********************
Set Me.Recordset = tbl
''********************
In you code:
Private Sub Form_open(cancel As Integer)
Dim strConnection, strSQL As String
Dim conn As ADODB.Connection
Dim tbl As ADODB.Recordset
Dim SourceCode As String
Dim myID As Variant
Set conn = New ADODB.Connection
strConnection = "ODBC;Driver={SQLserver};DSN=AccessDatabase;Server=Labor;DATABASE=Source;Trusted_Connection=Yes;"
conn.Open strConnection
myID = CInt(Me.OpenArgs)
SourceCode= Nz(DLookup("[SourceCode]", "Locaton", "[LOC_ID] = Forms!frmUtility![Site].value"), "")
If SourceCode<> "" Then
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & SourceCode & "_EmployeesBenefitsNew WHERE EmployeeID= " & myID
Else
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & "EmployeesBenefitsNew WHERE EmployeeID= " & myID
End If
Set tbl = New ADODB.Recordset
With tbl
Set .ActiveConnection = conn
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
''********************
Set Me.Recordset = tbl
''********************
conn.Close
Set conn = Nothing
Set tbl = Nothing
End Sub

Related

Split unpredictable length comma separated field not taking first record in series

I am running some code to split a slash-separated field into multiple rows, but the first value in the series is not carrying over. Does anyone know what I'm missing. Also, Rows that only have one record are not carrying over.
Public Sub ReformatTable()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsADD As DAO.Recordset
Dim strSQL As String
Dim strMPG, strBusinessName, strCustomerNumber, strCustomerName, strCountStartDate, strCCStatus As String
Dim strSplitMPG As String
Dim varData As Variant
Dim i As Integer
Set db = CurrentDb
' Select all eligible fields (have a comma) and unprocessed (SPLIT_MPG is Null)
strSQL = "SELECT BUSINESS_NAME, CUSTOMER_NUMBER, CUSTOMER_NAME, COUNT_START_DATE, CC_STATUS, MPG, SPLIT_MPG FROM [tmStarCycleCountStatuses_SlashesforCommas] WHERE ([MPG] Like ""*/*"") AND ([SPLIT_MPG] Is Null)"
Set rsADD = db.OpenRecordset("tmStarCycleCountStatuses_SlashesforCommas", dbOpenDynaset, dbAppendOnly)
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
With rs
While Not .EOF
strMPG = !MPG
strBusinessName = !BUSINESS_NAME
strCustomerNumber = !CUSTOMER_NUMBER
strCustomerName = !CUSTOMER_NAME
strCountStartDate = !COUNT_START_DATE
strCCStatus = !CC_STATUS
varData = Split(strMPG, "/") ' Get all comma delimited fields
' Update First Record
.Edit
!SPLIT_MPG = Trim(varData(0)) ' remove spaces before writing new fields
.Update
' Add records with same first field
' and new fields for remaining data at end of string
For i = 1 To UBound(varData)
With rsADD
.AddNew
!MPG = strMPG
!SPLIT_MPG = Trim(varData(i)) ' remove spaces before writing new fields
!BUSINESS_NAME = strBusinessName
!CUSTOMER_NUMBER = strCustomerNumber
!CUSTOMER_NAME = strCustomerName
!COUNT_START_DATE = strCountStartDate
!CC_STATUS = strCCStatus
.Update
End With
Next
.MoveNext
Wend
.Close
rsADD.Close
End With
Set rsADD = Nothing
Set rs = Nothing
db.Close
Set db = Nothing
End Sub
I can't post images yet due to reputation constrictions, but here are some links.
Here's the multiple after the code:
https://s9.postimg.org/fn3u70b5b/Multiple.jpg
Here's the single records after code run:
https://s10.postimg.org/bfq9z4snt/Singles.jpg
I feel like there's something super simple that I'm missing here, but it looks like I'm already taking the MPG over, so i'm curious as to why I'm not getting the singles or the first of the series. Any help would be appreciated! Thank you.
It looks right to me, except that you have to declare like this:
Dim strMPG As String
Dim strBusinessNames As String
Dim strCustomerNumbers As String
Dim strCustomerNames As String
Dim strCountStartDates As String
Dim strCCStatus As String
I guess you will have to insert some lines with Debug.Print .. to narrow down the happenings.
Got it. Ended up changing my approach. This code will work. The pattern, regardless of length, would always be the same, so I used a Right/Left combo and integers
Public Sub ReformatmStarCycleCountStatusesTable()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Dim strMPG As String
Dim strBusinessName As String
Dim strCustomerNumber As String
Dim strCustomerName As String
Dim dteCountStartDate As Date
Dim strCCStatus As String
Dim strSplitMPG As String
Dim intRemainingLength As Integer
Dim intInitialLength As Integer
Dim intStartPoint As Integer
Dim varData As Variant
Set db = CurrentDb
DoCmd.SetWarnings False
' Select all eligible fields (have a comma)
strSQL = "SELECT * FROM [mStar Cycle Count Statuses] WHERE [PRODUCT_FILTER_VALUE] is not null"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
With rs
While Not .EOF
strMPG = !PRODUCT_FILTER_VALUE
strBusinessName = !BUSINESS_NAME
strCustomerNumber = !CUSTOMER_NUMBER
dteCountStartDate = !COUNT_START_DATE
strCCStatus = !Status
intInitialLength = Len(strMPG)
intRemainingLength = intInitialLength
intStartPoint = 2
Do While intRemainingLength > 0
strSQL = "INSERT INTO tmStarCycleCountStatuses VALUES ('" & strBusinessName & "', '" & strCustomerNumber _
& "', #" & dteCountStartDate & "#, '" & strCCStatus & "', '" & Right(Left(strMPG, intStartPoint), 2) & "')"
DoCmd.RunSQL (strSQL)
intStartPoint = intStartPoint + 3
intRemainingLength = intRemainingLength - 3
Loop
intStartPoint = 1
.MoveNext
Wend
.Close
End With
DoCmd.SetWarnings True
Set rs = Nothing
db.Close
Set db = Nothing
End Sub

using a variable to Set rst

I'm trying to open a record set using a SQL string. I get run time error 3061 "Too Few Parameters." any help would be appreciated.
Dim stAppName As String
Dim stURL As String
Dim rst As Recordset
Dim dbs As Database
Dim stringToSearch As Integer
Dim strSQL As String
Set dbs = CurrentDb
stringToSearch = InputBox("What is your route #?", "Enter route #: ")
strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route=stringToSearch"
Set rst = dbs.OpenRecordset(strSQL)
Please change the code line of strSQL as follows, as suggested by Fionnuala you need to use variable outside the quotes.
Assuming Route field is Text data type, we need to put single quote for strings, if its number no single quote, for dates put # instead of single quote
strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route='" & stringToSearch & "'"
It's a little sample, maybe it can help you
Public Function fn_SQL_dbOpenRecordset(Optional vsql As String = "") As Recordset
Dim dbs As DAO.Database
Dim rs As Recordset
On Error GoTo END_CODE
'Set the database
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset(vsql, dbOpenForwardOnly) 'you can use: dbOpenDynamic; dbOpenSnapshot; dbOpenTable
Set fn_SQL_dbOpenRecordset = rs
Exit Function
END_CODE:
Set fn_SQL_dbOpenRecordset = Nothing
End Function
Public Sub Program_Test()
On Error GoTo ERROR_SUB
Dim rs As Recordset
Dim sName As String
sName = "Joe"
sName = "'" & sName & "'" 'WARNING: BE CAREFUL WITH SQL INJECTION !!! Google it
Set rs = fn_SQL_dbOpenRecordset("select * from table1 d where PersonName = " & sName)
Dim i As Long
i = 0
While Not rs.EOF
Debug.Print rs(0).Value & " - " & rs(1).Value
rs.MoveNext
Wend
ERROR_SUB:
On Error Resume Next
If Not rs Is Nothing Then rs.Close
Set rs = Nothing
End Sub

How to check for record by using ID, then if record exists update if not add new record

I've create an excel userform to collect data. I have connected it to Access to dump the data. However I want to update Access every time a user presses the submit button.
Basically I need the Select statement to determine an id existence, then if it doesn't exists I need to use the INSERT to add the new row. I'm very new with any SQL so any help would be great.
Here is the code I have now, I need to adapt it to ADO.
Sub Update()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim StrSql As String
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:="Foam", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
StrSql = "SELECT * FROM Foam WHERE FoamID = " & txtMyID
Set rst = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)
If (rst.RecordCount = 0) Then
DoCmd.RunSQL "INSERT INTO Foam (ID, Part, Job, Emp, Weight, Oven) VALUES " & _
"(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "', '" & txtField3 & "', '" & txtField4 & "', '" & txtField5 & "' );"
End If
' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End With
End Sub
I revised your code sample just enough to get it working on my system and tested this version in Excel 2007.
When I use a value for lngId which matches the id of an existing record, that record is opened in the recordset and I can update the values of its fields.
When lngId does not match the id of an existing record, the recordset opens empty [(.BOF And .EOF) = True]. In that situation, I add a new record and add the field values to it.
Sub Update()
Const TARGET_DB As String = "database1.mdb"
Dim cnn As ADODB.Connection
Dim MyConn As String
Dim rst As ADODB.Recordset
Dim StrSql As String
Dim lngId As Long
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
lngId = 4
StrSql = "SELECT * FROM tblFoo WHERE id = " & lngId
Set rst = New ADODB.Recordset
With rst
.CursorLocation = adUseServer
.Open Source:=StrSql, ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdText
If (.BOF And .EOF) Then
' no match found; add new record
.AddNew
!ID = lngId
!some_text = "Hello World"
Else
' matching record found; update it
!some_text = "Hello World"
End If
.Update
.Close
End With
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
Using VBA, here is a sample of how to query for a certain ID to check if it exists. If it does not then add it via an INSERT statement:
Dim rs As DAO.Recordset
Dim StrSql As String
StrSql = "SELECT * FROM MyTable WHERE ID = " & txtMyID
Set rs = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)
If (rs.RecordCount = 0) Then
DoCmd.RunSQL "INSERT INTO MyTable (ID, Field1, Field2) VALUES " & _
"(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "');"
End If

Display Recordset in New Form

The following code takes a parameter from a form and passes it to a stored procedure in vba. I am returning the values correctly and the stored procedure works when using debug.Print. Now I need to display the results of the stored procedure in the form "cat_percent_match". All this happens when the button is clicked. The code below does open the form, but now I need to pass the record set to it and display the results.
Any help is greatly appreciated.
Dim Cmd1 As ADODB.Command
Dim lngRecordsAffected As Long
Dim rs1 As ADODB.Recordset
Dim intRecordCount As Integer
'-----
Dim cnnTemp As ADODB.Connection
Set cnnTemp = New ADODB.Connection
cnnTemp.ConnectionString = "DRIVER=SQL Server;SERVER=***;" & _
"Trusted_Connection=No;UID=***;PWD=***;" & _
"Initial Catalog=IKB_QA;"
cnnTemp.ConnectionTimeout = 400
'Open Connection
cnnTemp.Open
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp
'---
With Cmd1
Dim localv As Integer
Dim inputv
localv = [Forms]![Start]![Selection]![cat_code]
.CommandText = "dbo.ix_spc_planogram_match_cat_percent " & inputv
.CommandType = adCmdStoredProc
Set inputv = Cmd1.CreateParameter("#deptcode", 3, 1, 10000, localv)
Cmd1.Parameters.Append inputv
Set rs1 = Nothing
Set rs1 = Cmd1.Execute
DoCmd.OpenForm "Cat_Percent_Match"
End With
End Sub
The relevant article is http://support.microsoft.com/kb/281998
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Use the ADO connection that Access uses
Set cn = CurrentProject.AccessConnection
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Customers"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
So in this particular case, you can try:
DoCmd.OpenForm "Cat_Percent_Match"
Set Forms.Cat_Percent_Match.Recordset = rs1

Search Functionality RunTime error 424 at Select

My requirement: To search for data in database, using VB forms and 3 text boxes.
1 TextBox, I will give Input (UserName)
1 TextBox for Location
1 TextBox for displaying output
My code is
Private Sub CommandButton3_Click()
Dim Cn As ADODB.Connection '* Connection String
Dim oCm As ADODB.Command '* Command Object
Dim sName As String
Dim rs As ADODB.Recordset
Dim uname As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set oCm = New ADODB.Command
oCm.ActiveConnection = Cn
‘Record Set
Set rs = New ADODB.Recordset
‘Select Operation
rs.Open "SampleTable", Cn, adOpenKeyset, adLockPessimistic, adCmdTable
uname = rs("UserName")
rs.Open "Select * from SampleTable where uname = '" & text1.Text & "'", ActiveConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
**'Display the Output in TextBox3**
TextBox3.Text = rs("UserName") + rs("Location")
rs.Close
Cn.Close
End Sub
I can understand the population of data is not happening so getting a RunTime error 424 at Select statement. How can I retrieve the data for the corresponding Input given?
You do not need to open the table; rs.Open "SampleTable" before searching it.
Not sure what this is for; uname = rs("UserName")
You should just run; rs.Open "Select * ... (Running the .Open on the same RS twice without closing the first is probably whats causing your error)
You should escape your input; replace$(text1.Text, "'", "''")
You should check for rs.EOF after the .open
Use & not + for concatenating strings
update
sub xxx
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = replace$(text1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
if (rs.eof) then
msgbox "no match"
else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
end if
set rs = nothing
Cn.Close
set cn = nothing
end sub