Access VBA Update Form Textbox With Sub Parameter - vba

I'm having an issue with figuring out how to update my forms textbox with the value I ended with in the procedure. If a messagebox is used the output is fine. However, I want the user to be able to click the button and the textbox on that form be updated with the answer.
Private Sub btnTotalGuests_Click()
Call CalculateTotalGuestsForEachService
End Sub
Here is the procedure
Public Sub CalculateTotalGuestsForEachService()
'Declare variables
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim intTotalParty As Integer
Dim intID As Integer
'Set the current database
Set db = CurrentDb
'Set the recordset
intID = InputBox("Enter the Service ID (1-6)", "Service ID")
Set rst = db.OpenRecordset("Select Orders.* From Orders Where ServiceID =" & intID)
'Cycle through the records
Do While Not rst.EOF
If Not IsNull(rst!NoInParty) Then
intTotalParty = intTotalParty + rst!NoInParty
End If
rst.MoveNext
Loop
'Display total amount
txtTotalGuests.Text = intTotalParty 'Wondering how to display this in the textbox on the form.
'Close the recordset
rst.Close
Set rst = Nothing
Set db = Nothing
End Sub

Don't use Text property. You want Value property and since Value is default, don't even need to explicitly reference. Presume CalculateTotalGuestsForEachService is in the form module so can use Me.txtTotalGuests.
Consider domain aggregate function instead of looping recordset.
Dim intID As Integer
intID = InputBox("Enter the Service ID (1-6)", "Service ID")
Me.txtTotalGuests = DSum("NoInParty", "Order", "ServiceID =" & intID)

Related

Trying to add a record or edit if it is a duplicate in VBA

I'm creating a form that is intended to add records to a data table or edit existing record if the ID is a duplicate. `
UPDATE**
I've figured out how to make this work. Sort of. My current code is
`Option Compare Database
Private Sub btnAddRecord_Click()
'Declare variables
Dim db As DAO.Database
Dim rst As Recordset
Dim intID As Integer
'Set the current database
Set db = Application.CurrentDb
'Set the recordset
Set rst = db.OpenRecordset("tblHOAFees", dbOpenDynaset)
'Set value for variable
intID = lstAccountID.Value
'Finds the Account ID selected on the form
With rst
rst.FindFirst "AccountID=" & intID
'If the record has not yet been added to the form adds a new record
If .NoMatch Then
rst.AddNew
rst!AccountID = intID
rst!HOAID = txtHOAID.Value
rst!Location = txtLocation.Value
rst!House = chkHouse.Value
rst!Rooms = txtRooms.Value
rst!SquareFeet = txtSquareFeet.Value
rst!HOAFees = txtHOAFees.Value
rst.Update
'If the Account ID is already in the form edits the record
Else
rst.Edit
rst!AccountID = intID
rst!HOAID = txtHOAID.Value
rst!Location = txtLocation.Value
rst!House = chkHouse.Value
rst!Rooms = txtRooms.Value
rst!SquareFeet = txtSquareFeet.Value
rst!HOAFees = txtHOAFees.Value
rst.Update
End If
End With
'Closes the recordset
rst.Close
Set rst = Nothing
Set db = Nothing
End Sub`
This adds or edits records. However, after adding a record and trying to close my form I get an error message about how the table can't be saved because it created a duplicate. When I click through all the error messages re-open the table, the records are still on there anyway. I can't seem to figure out how to get around this.Error Image

Trying to populate a ComboBox in Access ContinuousForm (different recordset for each row) by calling a function from the ControlSource in the designer

I am trying to populate a Combo Box on a continuous form by calling a function in the Control Source field of the data tab in the Combo Cox designer. Each Combo Box on each row will have a different recordset based upon the different parameters that are passed into each function call.
The problem is it is not populating the Combo Boxes.
In the designer:
=LaterRevisions([DocumentCode],[LadRevision],[LadId])
The function:
(Note I have commented out the return type in the function definition since with this it doesn't even appear to execute the function!? (doesn't trip a breakpoint in the body of the function))
Public Function LaterRevisions (DocumentCode As String, LadRevision As String, LadId As Integer) 'As ADODB.Recordset
On Error GoTo ErrHandler
Dim Record As Variant
Dim dbs As Object
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim qdf As QueryDef
Dim sql As String
Set dbs = CurrentDb()
Set qdf = dbs.QueryDefs("qryLaterRevisionsByRow")
sql = qdf.sql
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandText = sql
With .Parameters("DocumentCode")
.Type = adVarChar
.Value = DocumentCode
End With
With .Parameters("LadRevision")
.Type = adVarChar
.Value = LadRevision
End With
With .Parameters("LadId")
.Type = adInteger
.Value = LadId
End With
End With
cmd.Execute
Set rs = New ADODB.Recordset
With rs
.CursorLocation = adUseServer
.Open cmd, , adOpenForwardOnly, adLockReadOnly
End With
If Not rs.BOF And Not rs.EOF Then
Debug.Print rs.RecordCount ' does get records
'Set Me.[cboLatestrevision].Recordset = rs ' will set this recordset (but sets all rows to the same in continuous form)
Set LaterRevisions = rs ' function returns individual recordset for each row, but doesn't populate the combo
End If
ExitHandler:
Exit Function
ErrHandler:
' handle error
Resume ExitHandler
End Function
Despite when stepping through the code it clearly shows the recordset being populated, and when calling the function from the Form_Load event, it populates a recordset (hence the function is returning one) (see test code below), it doesn't populate the Combo Box.
Private Sub Form_Load()
Dim myVar As ADODB.Recordset
Set myVar = LaterRevisions("XXX", "YYY", 999)
For myI = 1 To myVar.RecordCount
Debug.Print myVar.Fields("LatestRevision") ' prints correct values
myVar.MoveNext
Next myI
End Sub
The saved query (qryLaterRevisionsByRow):
PARAMETERS DocumentCode Text ( 255 ), LadRevision Text ( 255 ), LadId Long;
SELECT tblLaterRevisions.LatestRevision
FROM tblLaterRevisions
WHERE (((tblLaterRevisions.LatestRevision)>[LadRevision]) AND ((tblLaterRevisions.DocumentCode)=[DocumentCode]) AND ((tblLaterRevisions.LadId)=[LadId]));
I have these references:
I'm using Windows 7 Enterprise, MS Access 2010

How to return multiple values from table based on specific item that I entered?

I tried to use Tooling_No_AfterUpdate() for both Sub and Function but it prompt me 'Ambiguous name detected' as I know that I can't use the same identifier. Then, I changed the identifier and set it to public function but it doesn't work and prompt me 'User-defined type not defined'.
I'm creating a form for user to enter the tooling number to know the storage location where it can be more than one location. I tried to use ADODB.Recordset to get data from my asset table. So here's what I tried:
Private Function Tooling_No_Enter() As ADODB.Recordset
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
Set Tooling_No_Enter = CurrentProject.Connection.Execute("select FirstName, LastName from Employees")
End Function
Private Sub Tooling_No_AfterUpdate()
Dim strStorage_Location_1 As String
Dim strStorage_Location_2 As String
Dim strStorage_Location_3 As String
Dim strStorage_Location_4 As String
Dim strStorage_Location_5 As String
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
Set rst = Tooling_No_Enter()
Do While Not rst.EOF
strStorage_Location_1 = rst!Storage_Loacation_1
strStorage_Location_2 = rst!Storage_Loacation_2
strStorage_Location_3 = rst!Storage_Loacation_3
strStorage_Location_4 = rst!Storage_Loacation_4
strStorage_Location_5 = rst!Storage_Loacation_5
Debug.Print strStorage_Location_1 + vbCrLf + strStorage_Location_2 + vbCrLf + strStorage_Location_3 + vbCrLf + strStorage_Location_4 + vbCrLf + strStorage_Location_5
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
End Sub
After that, users able to choose the location while the chosen location will be recorded into asset table and transaction table and these are the parts i can't figure it out.
You are using the wrong method to open ADODB recordset. For one thing, Execute is used for action SQL (DELETE, UPDATE, INSERT).
One way to use a recordset object in multiple procedures is to declare recordset variable in module header. Example shows declaring and setting and opening connection and recordset objects which are then referred to in another procedure not shown.
Option Compare Database
Option Explicit
Public strOldLabNum
Dim cn As ADODB.Connection
Dim rsOldSample As ADODB.Recordset
___________________________________________________
Private Sub cbxOldLabNum_AfterUpdate()
Set cn = CurrentProject.Connection
Set rsOldSample = New ADODB.Recordset
strOldLabNum = Me.tbxOldYear & "A-" & Me.cbxOldLabNum
'select old sample info from table zSample
rsOldSample.Open "SELECT * FROM zSample WHERE LabNum='" & strOldLabNum & "';", _
cn, adOpenStatic, adLockPessimistic
End Sub

changing sql string based on active userform

I have a SQL query that I'm calling from a couple of different forms using the ctrl as object method. It works fine, but when I run it from a click event it will also open whichever form isn't currently loaded. The query returns the results I want, it just does it to both forms at the same time regardless of which is loaded.
Only one form is loaded at a time. A drop down list called Team exists on both forms. The query passes the currently selected item from that drop down list to return a list of agents assigned to that team.
I know that part of the issue is my query using an or statement that refers to values on both forms, but I'm not sure how to change it to reference the active form.
Attendance and reporting are the names of the two UserForms currently calling this query. Both of them have combobox controls named Team. I've tried activeform, etc. But I can't seem to find a way to make it work.
Sub agents(ctrl As Object)
database_connect
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim Counter As Long
SQLStr="select distinct[Agentname] from dbo.[Attendance] Where [Team]='" & _
attendance.Team.Value & "' or [Team] ='" & Reporting.Team.Value & "'"
If appconn.State = 0 Then
Call database_connect
End If
rs.Open SQLStr, appconn, adOpenStatic
With ctrl
Do
.AddItem rs![Agentname]
rs.MoveNext
Loop Until rs.EOF
End With
rs.Close
database_Disconnect
Set rs = Nothing
Exit Sub
End Sub
1) Well first off to refer to controls you have to have the form loaded.
2) Youre referring to controls in the oddest way. Review AND save this URL http://access.mvps.org/access/forms/frm0031.htm
3) If one form is closed your query might always return nothing. Is this a desired output?
For anyone who may find this looking for something similar, this is the solution I used.
I used a Function to test if a userform is loaded or not.
Public Function IsLoaded(formName As String) As Boolean
Dim frm As Object
For Each frm In VBA.UserForms
If frm.Name = formName Then
IsLoaded = True
Exit Function
End If
Next frm
IsLoaded = False
End Function
Then adjusted my above code like so
database_connect
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim Counter As Long
If IsLoaded("Attendance") Then
SQLStr = "select distinct[Agentname] from dbo.[Attendance] Where [Team] ='" & attendance.Team.value & "'"
ElseIf IsLoaded("Reporting") Then
SQLStr = "select distinct[Agentname] from dbo.[Attendance] Where [Team] ='" & Reporting.Team.value & "'"
End If
If appconn.State = 0 Then
Call database_connect
End If
rs.Open SQLStr, appconn, adOpenStatic
With ctrl
Do
.AddItem rs![Agentname]
rs.MoveNext
Loop Until rs.EOF
End With
rs.Close
database_Disconnect
Set rs = Nothing
Exit Sub
now it works like a charm!

Updating Multiple Rows using .edit in vba access 2007

I hope I can ask this right.
I have a listbox on a form (access 2007) and have it set on "simple" so I can multi-select.
I am trying to update multiple columns in a table, based on the selections in the listbox. I have a few textboxes that I want to use as the information to update the table.
I have a loop that is only updating the first record in the table no matter how many items are selected.
I think I understand why it's only updating the first record from my loop but am not sure
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("Table1", dbOpenDynaset)
Dim i As Variant
For Each i In Listbox.ItemsSelected
With rs
.Edit
!Col1 = Me.Textbox1
!Col2 = Me.Textbox2
!Col3 = Me.Textbox3
.Update
End With
Next
I assume this is because I am not specifying the "where" in the loop I want my table updated, but I have no idea how to do this in this loop. I would have 3 columns in the listbox (at positions 1, 3 and 4) that all need to be included to specify which records in the table need to be updated. I have tried this as well using an sql query with DoCmd.RunSql but it seems impossible to change the focus of the ListIndex mid-query. Aplogies for my lack of knowledge I am pretty new to visual basic. Please Help
Simplified example how I would give it a try if I understood correctly:
Sub MultiSelect_Listbox()
Dim lCnt as Long
dim lID as long
dim sSQL_Update as string
dim sText_1 as String
dim sText_2 as String
dim sText_3 as String
dim bSuccess as Boolean
sText_1 = me.txt_Textbox_1
sText_2 = me.txt_Textbox_2
sText_3 = me.txt_Textbox_3
With Me.lst_Listbox
For lCnt = 1 To .ListCount
If .Selected(lCnt) Then
lID = .Column(0, lCnt - 1)
'Example update for 1 column
sSQL_Update = "UPDATE T_TABLE SET COL_TEXT_1 = '" & sText_1 & "' WHERE ID = " & lID & ";"
bSuccess = Update_Statement(sSQL_Update)
End If
Next
End With
End Sub
Public Function Update_Statement(sUpdate_Stmt) As Boolean
Dim db As Database
Set db = CurrentDb
db.Execute (sUpdate_Stmt)
Update_Statement = True
End Function