MS Access: Link listbox to textbox - forms

I have a textbox and listbox, one is for entering a new topic in a help form while the other looks up those new topics. I would like to be able to present the finished topics in both the textbox and listbox simultaneously to edit or lookup as well write new records in the help form. The listbox provides functionality to view which records there are now.
I find if I put nothing in and I go to a new record the prev/next buttons will stop working, maybe there is a control I need to add to keep it from freezing or to refresh? Normally I press esc to get out of a new record edit and return to others but that does not work as usual.
Or how else may I point to the listbox's current record source?
I currently have this code:
Private Sub List35_AfterUpdate()
DoCmd.GoToRecord acDataForm, "Help Form_Editor2", acGoTo, Me.List35.ListIndex + 1
Me.List35 = Me.List35.Column(0, Form.CurrentRecord - 1)
Dim index As Integer
index = Form.CurrentRecord - 1
Me.Text53 = Me.List35.Column(Me.List35.ListIndex + 1, index)
End Sub
I keep getting some of the items to read but others are null. I have about 8 items in the source table... what is going wrong? Why would there be nulls?
Another issue after getting this updated. When the code is setup the recordset starts at new when I allow additions and edits on the form. The code displays the list item as it should but the other items will not activate from the requeried listbox item. What might correct this issue?
Private Sub List35_AfterUpdate()
Dim myTitle As String
With Me.List35
If .ListIndex > -1 Then
'Use this one if you are using bound column
myTitle = .Column(1, Form.CurrentRecord)
'use this if you want something other than the bound column
'and you have more than one column in the list (hidden or not)
'nId = .Column(1, .ListIndex)
Me.RecordSource = "SELECT * FROM FormsHelpTable WHERE HelpTitle = '" & myTitle & "'"
Me.Text53.Value = myTitle
Else
Me.RecordSource = "SELECT * FROM FormsHelpTable WHERE HelpTitle IS NULL"
'Me.Text53.Value = "(New)"
End If
End With
Me.Requery
End Sub

This checks for ListIndex. It will be -1 if you don't have anything selected.
Private Sub List35_AfterUpdate()
Dim index As Integer
With Me.List35
If .ListIndex > -1 Then
DoCmd.GoToRecord acDataForm, "Help Form_Editor2", acGoTo, .ListIndex + 1
.Value = .Column(0, Form.CurrentRecord - 1)
index = Form.CurrentRecord - 1
Me.Text53 = .Column(.ListIndex + 1, index)
End If
End With
End Sub
I'm not sure what all your code is trying to do, so I didn't make any other adjustments other than to reduce all references to List35 to a single With statement.
I normally do something like this:
Private Sub List35_AfterUpdate()
Dim nId As Long
With Me.List35
If .ListIndex > -1 Then
'Use this one if you are using bound column
nId = .Value
'use this if you want something other than the bound column
'and you have more than one column in the list (hidden or not)
'nId = .Column(1, .ListIndex)
Me.RecordSource = "SELECT * FROM TableName WHERE Id = " & nId
Else
Me.RecordSource = "SELECT * FROM TableName WHERE Id IS NULL"
End If
End With
Me.Requery
End Sub

Related

Navigate programmatically through the records of a continuous form

I would like to navigate through the records of a continuous form in Access 97. I don't find how to do it. This is what I tried:
Me.RecordSetClone.MoveFirst moves to the first record logically, but not in the UI. Also the CurrentRecord property does not change.
I cannot set the CurrentRecord property, it is readonly. Me.CurrentRecord = 1 gives an error.
DoCmd.GoToRecord Record:=acFirst seems to have no effect.
What is the correct way to move to the first record in a continuous form (and to the next/previous)?
Use the Bookmark property of RecordsetClone and Form.
Caveat: I'm pretty sure all this worked in Access 97, but that was a really long time ago.
Sub DemoNavigate()
Dim RS As DAO.Recordset
Set RS = Me.RecordsetClone
RS.MoveFirst
' or
RS.AbsolutePosition = 0
' Navigate in form
Me.Bookmark = RS.Bookmark
' next record
RS.MoveNext
' or
RS.AbsolutePosition = 1
Me.Bookmark = RS.Bookmark
' Move to searched record
RS.FindFirst "someField = 42"
Me.Bookmark = RS.Bookmark
End Sub

MS Access combo box

I'm new to forms in MS access and I've created a form with a combo box that auto fills a few things i'm looking for, basically and name, phone #, and check out date. I have added another text box for "check in date" and I'm able to input the date but it will update the first record in the table that I'm pulling information from and not the record that the auto fill combo box displays. would anyone know a fix to update the record that the auto fill display versus the top record of the table?
Private Sub Combo0_Change()
Me.txtfname = Me.Combo0.Column(1)
Me.txtlname = Me.Combo0.Column(2)
Me.txtphone = Me.Combo0.Column(3)
Me.txtpump = Me.Combo0.Column(4)
Me.txtdateissue = Me.Combo0.Column(5)
Me.txtduedate = Me.Combo0.Column(6)
Me.txtCheckInDate = Me.Combo0.Column(7)
End Sub
Private Sub Combo0_Click()
End Sub
Private Sub txtCheckInDate_Change()
End Sub
get the source of Combo0 combobox, then in Private Sub txtCheckInDate_Change() function, change its source to that source + your filter, like
Me.Combo0.RowSource = "[Existing Combo Source SQL]" & _
" WHERE [YourDateField] = #" & me.txtCheckInDate & "#"

Error 2427 "You entered an expression that has no value." in Access form (VBA)

I am using Access VBA, and I have two forms (form1 and form2), in form 1 I have a listbox control (form1.modifiable49). I choose a list item and with a button control click I open the second form (form2),
In the second form I have some table columns, and I have a textbox where I store my variable, I would like to open form2 with the element that equals the value of modifiable49
I have:
Private Sub Form_Load()
Me.Texte = [Forms]![Form1]![Modifiable49]
Me.Filter = "[id_parcelle]=" & Texte
Me.FilterOn = True
End Sub
but when I choose the value in the listbox and I excute I get error 2427:
You entered an expression that has no value.
The expression may refer to an object that has no value, such as a form, a report, or a label control.
This will not fail and will list the value of Texte for you to investigate:
Private Sub Form_Load()
Me!Texte.Value = [Forms]![Form1]![Modifiable49].Value
Debug.Print "Texte:", Me!Texte.Value
Me.Filter = "[id_parcelle]=" & Me!Texte.Value & ""
' or, if Texte is a string:
' Me.Filter = "[id_parcelle]='" & Me!Texte.Value & "'"
Me.FilterOn = Not IsNull(Me!Texte.Value)
End Sub

Access fields in form using vba

I created a query and a form in Microsoft Access 2010. The form, named TEST, looks as follows:
Field1 Field2
a 200
b 400
In VBA I tried to access the different fields in the form:
Form_TEST.Field1....
I want to save the values 200 and 400 in an integer variable (Dim a As Integer) and print it using MsgBox. How can i achieve that??
You can use the Me as the open form and assign the variable if you know the name of the text box.
Dim intValue as Integer
'If text box name = TextBox1
intValue = Me.TextBox1.Value
I'll try to help you.
I understood you created the form with the wizard putting the 2 fields on the form.
What is not clear is the View that you are using.
Well, your form can be displayed in different ways:
- Single form
- Continuous forms
- Datasheet
This is defined by the Default View property.
To see the properties of you form press F4 to see properties and select "Form" as the object that you want to see.
If your form is Single Form or Continuous form you can access the two fields you put on it simply addressing them.
Click on the controls you put on the form and press F4 to see the control name.
CASE 1 - SINGLE FORM VIEW
Let's assume that your controls are named Text1 (200) and Text2 (400) and for convenience your form is a single form.
So you can refer to values in the 2 controls writing
Dim intText1 As Integer, intText2 As Integer
intText1 = Me.Text1.Value
intText2 = Me.Text2.Value
The .Value property is not mandatory cause it's the default property.
At this point you can print out intText1,2 with a MsgBox
MsgBox "Text1 = " & CStr(intText1)+ " - Text2 = " & CStr(intText2)
This will show Text1 = 200 - Text2 = 400
CASE 2 - CONTINUOUS FORMS VIEW
Let's now assume that your view is Continuous form.
So the field that contains 200 and 400 is just one but each record (row) is a form repeated as many times as the number of records.
In this case to access all the records and store them to an array you can use this in the Form_Load event (you can access it by the Control Properties Window - F4)
Option Explicit
Option Base 1 ' Set the base index for vectors to 1
Dim rst as DAO.Recordset ' Define a recordset to allocate all query records
Dim Values as Variant ' Define a variant to allocate all the values
set rst = me.RecordsetClone ' Copy all records in rst
rst.MoveLast ' Go to last record
intNumRecords = rst.RecordCount ' Count records
rst.MoveFirst ' Go back to recordset beginning
ReDim Values(intNumRecords) ' Resize Values to allocate all values
i = 1
Do While Not rst.EOF ' Cycle over all records
Values(i) = rst!FieldName ' FieldName is the name of the field of
' the query that stores 200 and 400
i = i + 1 ' Move to next array element
rst.MoveNext ' Move to next record
Loop
rst.Close ' Close recordset
set rst = Nothing ' Release memory allocated to rst
for i = 1 To intNumRecords ' Show easch value as message box
MsgBox Values(i)
next i
NOTES
Please NOte that this solution works if you have less than 32767 records to show (the maximum integer with sign that you can store).
The msgbox obliges you to press OK at each value. It's not so comfortable.
Please tell me if it's what you were looking for.
Bye,
Wiz

Displaying a recordset on a form in Access 2010 using VBA

I'm developing a data retrieval application in Access 2010 in which the user chooses which table, columns, and rows to view by selecting listbox entries. The VBA code generates a SQL statement from these choices and then creates an ADBDB.Recordset object from this.
How can I display the recordset records in Access? None of the grid controls work in Access 2010 and the subform just isn't designed for this purpose. Can someone recommend another strategy?
You could save the SELECT statement as a named query, then open the query as a datasheet. It's not really a form, but somewhat form-like.
Call DatasheetFromSql(strSql)
Public Sub DatasheetFromSql(ByVal pSql As String)
Const cstrQuery As String = "qryDiscardMe"
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strMsg As String
On Error GoTo ErrorHandler
Set db = CurrentDb
db.QueryDefs.Delete cstrQuery
Set qdf = db.CreateQueryDef(cstrQuery, pSql)
DoCmd.OpenQuery cstrQuery, , acReadOnly
ExitHere:
On Error GoTo 0
Set qdf = Nothing
Set db = Nothing
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 3265 ' Item not found in this collection. '
Resume Next
Case Else
strMsg = "Error " & Err.Number & " (" & Err.description _
& ") in procedure DatasheetFromSql"
MsgBox strMsg
GoTo ExitHere
End Select
End Sub
I opened the query read-only. If you want to allow users to edit the data returned by their custom queries, I would not recommend this approach. Instead I would invest the effort in the approach HK1 offered because it can support better control of the user data changes.
With the query opened as a datasheet, you can use Screen.ActiveDatasheet to inspect its properties. At least some of the methods are also available to you. For example you could resize/reposition the datasheet like this:
Screen.ActiveDatasheet.Move Left:=0, Top:=0, Width:=(4 * 1440), Height:=(3 * 1440)
The units are twips (1440 twips / inch), so that would make the width 4 in., height 3 in., and move it to the upper left corner of the Access window.
Here's what I think you'll have to do to get this kind of functionality.
You'll first need to create enough of the correct controls on a form to handle every possible scenario. You'll then need to set the form to be a datasheet form so that it appears as a grid.
Now set the controlsource on your controls to correspond with one of the fields in the recordset. On every control that is not in use needs to have it's ColumnHidden property set to true. You'll also have to change the caption of the associated label to show the appropriate column name for each control that will be visible.
Now, bind that form to your ADO recordset object.
Me.Recordset = rst
'or
Me.Subform1.Form.Recordset = rst
Is this a perfect solution? Most certainly not. Access doesn't have anything that compares to the DataGridView in .Net or even to the Grid controls that are used in VB6. In my opinion, you're really pushing the limits of Access to try to get this sort of functionality. It's like swimming upstream. You'll find that everything you do is going to be fairly difficult and some things just aren't going to be possible.
for an ADP Project where you can't have local MS Access query definitions, you can create a datasheet form with multiple textboxs named txt1, txt2,.... txt30 and labels name lbl1 ... lb30 and this code will set the form.recordsource and set the textbox.controlsource and the label.caption to the appropriate fields from an ADO recordset object. This form will allow you to view your ADO Recordset similar to the Docmd.OpenQuery method.
You must pass the ADO recordset's SQL statement to the form using the OpenArgs property of the form. the code below shows the VBA code to call\open the form (which shows the ADO Recordset like a query) and pass your sql string. The vba code on the form's load event will set all the control properties, resize the columns that have data and hide the columns that do not have a corresponding field from the ado recordset:
'stevekirchner 09/29/2012 Replace Access parameterized query with SQL Server in-line function
'DoCmd.OpenQuery "qry_SearchMaster_CaseTitles", , acReadOnly
strsql = "Select * from dbo.UDF__qry_SearchMaster_CaseTitles ('%" & Me.tbxSearchTerm.Value & "%') "
Call Display_ADO_Recordset_from_Datasheet_Form(strsql, "frm_Display_ADO_Recordset_Result1")
'create a non-form module and put the code for the sub Display_ADO_Recordset_from_Datasheet_Form
'and function fIsLoaded in it (this will allow you make several forms to view ADO recordset and
'call the code from one place\module):
Sub Display_ADO_Recordset_from_Datasheet_Form(sSQL As String, sFormName As String)
On Error GoTo Error_Handler
If fIsLoaded(sFormName) Then
DoCmd.Close acForm, sFormName
End If
DoCmd.OpenForm sFormName, acFormDS, , , acFormReadOnly, , OpenArgs:=sSQL
Exit_Sub:
Exit Sub
Error_Handler:
MsgBox Err.Description & " Error No: " & CStr(Err.Number)
Resume Exit_Sub
End Sub
Function fIsLoaded(ByVal strFormname As String) As Boolean
On Error GoTo Error_Handler
'Returns False if form is not open or True if Open
If SysCmd(acSysCmdGetObjectState, acForm, strFormname) <> 0 Then
If Forms(strFormname).CurrentView <> 0 Then
fIsLoaded = True
End If
End If
Exit_Function:
Exit Function
Error_Handler:
MsgBox Err.Description & " Error No: " & CStr(Err.Number)
fIsLoaded = False
Resume Exit_Function
End Function
'Create a datasheet view form (named frm_Display_ADO_Recordset_Result1) with 30 textboxes and 30
'30 labels named txt1 - txt30 and lbl1 - lbl30 and put this code in the form's module:
Option Compare Database
Private Sub Form_Load()
On Error GoTo Error_Handler
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rsClone As ADODB.Recordset
Dim strsql As String
Set conn = CurrentProject.Connection
Set rs = New ADODB.Recordset
strsql = Me.OpenArgs
rs.Open strsql, conn, adOpenStatic, adLockOptimistic
Set rsClone = rs.Clone
Call Update_Form_Controls("your text goes here", strsql, rsClone)
Exit_Sub:
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Exit Sub
Error_Handler:
MsgBox Err.Description & "; Error Number : " & Err.Number, vbOKOnly
Resume Exit_Sub
End Sub
Sub Update_Form_Controls(Header_Label As String, SQL As String, CloneRS As Recordset)
Dim rsCount As Integer
Dim i As Integer
On Error GoTo Error_Handler
Me.Form.Caption = Replace(SQL, "Select * From ", "Display: ")
rsCount = CloneRS.RecordCount
If rsCount <= 0 Then
MsgBox "The Query did not return any data to view", vbOKOnly
DoCmd.Close
Else
Me.Form.SetFocus
Me.RecordSource = SQL
i = 1
Do Until i = 31
Me("lbl" & i).Caption = ""
Me("txt" & i).ControlSource = ""
Me("txt" & i).ColumnHidden = True
i = i + 1
Loop
i = 1
With CloneRS
For Each Field In .Fields
On Error Resume Next
Me("lbl" & i).Caption = .Fields(i - 1).Name
Me("txt" & i).ControlSource = .Fields(i - 1).Name
Me("lbl" & i).Visible = True
Me("txt" & i).ColumnHidden = False
Me("txt" & i).SizeToFit
i = i + 1
'Debug.Print Field.Name
On Error GoTo 0
Next Field
End With
End If
Exit_Sub:
Me.Requery
Exit Sub
Error_Handler:
MsgBox Err.Description & "; Error Number : " & Err.Number, vbOKOnly
Resume Exit_Sub
End Sub
I don't use ADO but simply VBA, in which case above approach is wrong: one doesn't need any means for displaying an existing recordset in a form, but should on the contrary define an adequate recordset within the form !
Instead of creating MyDataBase.OpenRecordset ("SELECT … [SQL query] ;"), just set the form's RecordSource to the very same query definition:
Forms![MyDisplayForm].RecordSource = "SELECT … [SQL query] ;"
Forms![MyDisplayForm].Requery
For me this works perfectly (Windows 7 pro ×64 / MS Office pro ×64)