Setting Combobox Value With VBA MS Access - ms-access

I am trying to make a module to pass a single result of a query into a Combobox to be populated/displayed immediately on Form_Load event, but I keep getting the following error: Run-time error '2465' "Microsoft Access can't find the field 'MyCombo' referred to in your expression"
Query result is tested and returning the proper value. the problem is in the reference call to the MyCombo combobox.
This is my code below:
Public Function getSetRefNo() As String
Dim rs1 As DAO.Recordset
Dim currentformName As String
currentformName = Screen.ActiveForm.Name
Dim docidrefnoquery As String
Dim dociddefaultvalue As String
Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT ColA FROM TblA WHERE ColC = " & Forms(currentformName)![Combo25])
Do Until rs1.EOF = True
docidrefnoquery = rs1(0)
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
dociddefaultvalue = DLookup("RefNo", docidrefnoquery) 'RefNo here is the target column in the Query
Forms(currentformName)![MyCombo] = dociddefaultvalue 'MyCombo here is the Combobox Name
Debug.Print docidrefnoquery & " - " & dociddefaultvalue
End Function
on the targeted form, I use this code:
Private Sub Form_Load()
Call getSetRefNo
End Sub
after opening the targeted form, I receive the above mentioned error. I don't know what's wrong I tried to trace everything and it seems to be fine, I used the same chunk of codes in other places and worked fine. don't know what's wrong here to be honest. I would be grateful if you could help me elaborate what's going on.

I had to alter the form_load event like the following:
Private Sub Form_Load()
Me.TimerInterval = 30
End Sub
Private Sub Form_Timer()
Me.TimerInterval = 0
Call getSetRefNo
End Sub

Related

Unable to filter datasheet form after inserting value in ms access

I am using a datahseet subform in my main form for the realtime view of entries added in the table via the main form. This subform filters data on load event and checks with users windows username and compares it with data, it should only show data of respective owner. That means it willl filter the name field and shows only the entries made by the respective user(to unable users to edit each other's entries). It works well with the below code which I used in this datasheet form's vba :
Option Compare Database
Option Explicit
Dim GetUserName As String
Dim GetEmpID As String
Dim RecCount As String
Public Sub GetValues()
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
RecCount = DCount("[ID]", "Mau_con", "[AdvisorName] = '" & GetUserName & "'")
Set obj1 = Nothing
End Sub
Private Sub Form_AfterInsert()
Call Form_Load
End Sub
Private Sub Form_Load()
Call GetValues
If RecCount > 0 Then
Dim strOpen As String
strOpen = "[AdvisorName] = '" & GetUserName & "'"
Me.Filter = strOpen
Me.FilterOn = True
Me.Recordset.MoveLast
End If
End Sub
It filters the data on load but problems arises when a new user comes and login, then it will skip the if loop and will work normally, I tried to requery the form after making first entry by the new user & I also tried to call form_load in after insert event but both did not work.
But it filters the data once we close it and reopen it.
What is the best way to overcome this ?
Please ask if any other information needed.
Thanks in Advance.

not able to update access table field using VBA

I have a userform in access which submits the data to a table, there are two fields in table which I want to get populated automatically whenever user makes a new entry in form. I am using the below vba code with that form :
Option Compare Database
Public Function GetUserName() As String
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Function
Private Sub Form_BeforeInsert(Cancel As Integer)
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
End Sub
Private Sub Form_Load()
Me.DataForm.Form.Recordset.MoveLast
End Sub
Private Sub SaveBtn_Click()
RunCommand acCmdSaveRecord
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
End Sub
I am able to get the value in "owner" field but not in "AdvisorName" field.
What can be the possible reason behind this ?
is there any mistake in my code or is there any better method of doing this ?
The below code should commit both values to your table using a querydef. This is my preferred approach but there are other ways to do it as well. The qdf represents a sql string that can accept parameters from code. We are inserting the values of our variables directly into the sql string.
I copied the code from the save button to re-establish the form state after entry. This should bring the last record back up, but it will depend on the cursortype of the recordset whether the saved record is represented or not (it might go backwards).
Private Sub Form_BeforeInsert(Cancel As Integer)
Dim qdf As QueryDef
Dim Owner2 As String
Dim AdvisorName As String
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
Set qdf = CurrentDb.CreateQueryDef("", "INSERT INTO Mau_con (Owner, AdvisorName) VALUES ('" & Owner2 & "', '" & AdvisorName & "')")
qdf.Execute
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
Set qdf = Nothing
End Sub

Access 2010 - Error Handling Filter Subform

how can I disable the filter of a Datagridview, using VBA, if after filtering there is no record?
Here my first try:
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
If Me.RecordsetClone.RecordCount = 0 Then
MsgBox ("Kein Datensatz gefunden. Filter wird entfernt.")
Me.Form.FilterOn = False
Me.Form.Requery
End If
End Sub
Here is the second try:
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.Filter = Replace(Me.Filter, "[Tabelle1].", "")
Set rs = rs.OpenRecordset()
If rs.EOF Then
Cancel = True
End If
End Sub
In the second code I get the error 3061. The first code "works", but is finally not want I need.
Because:
I have 3 Forms. MAIN, Sub1 and Sub2.
In the MAIN are Sub1 , Sub2 and a single TextBox. The TextBox is call "psoudoID". Sub1 is a normal Form to show the details of the different recordsets and is placed on the top of the MAIN. Below Sub1 is Sub2. Sub2 is a Datagridview. When the user is clicking on a recordset on Sub2, the ID from Sub2 "goes" to the psoudoID and from there to Sub1. You understand?
Now is the problem, that the user can filter every column in Datagrid to find the recordset here needs and show all details above. But when the datagrid is empty after filtering , so Sub2 can't give an ID to the psoudoID and so on Sub1 is not displayed in MAIN much longer. The screen is empty on that place. By clicking the Filter-Button in grid, Sub1 is on the screen again.
I want to disable the filter by clicking "Ok" of a MsgBox or automatically and not by clicking the Filter-Button on gridview.
I hope you can understand my discribtion. And sorry for my bad English :-)
THX.
Vegeta
I believe you're having problems with filters being Null, and with using Me.Filter before the filter is actually applied. Also, re-assigning an object to a property/member of itself has caused problems for me before, so I try to avoid doing that.
The following should work:
Dim strOldFilter As String
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
Me.TimerInterval = 50
strOldFilter = Nz(Me.Filter, "")
End Sub
Private Sub Form_Timer
Me.TimerInterval = 0
If Me.Filter = strOldFilter Then Exit Sub
Dim rs As DAO.Recordset
Dim strFilter As String
strFilter = Nz(Me.Filter, "")
If strFilter = "" Then
'Handle this specific scenario
Exit Sub
End if
Set rs = Me.RecordsetClone
rs.Filter = Replace(strFilter, "[Tabelle1].", "")
Dim rsf as DAO.Recordset
Set rsf = rs.OpenRecordset
If rsf.EOF Then
Me.Filter = strOldFilter
End If
End Sub
Note the potential to cause infinite loops that repeat every 50 msec if you change a filter resulting in 0 records to another filter resulting in 0 records (but you shouldn't be able to have a filter resulting in 0 records if the function works)

Access query need to bypass "enter parameter value" error with a msg box saying field not found

I have a simple query tied to a command button that shows a summary of the values in a particular field. It's running on a table that changes with each use of the database, so sometimes the table will contain this field and sometimes it won't. When the field (called Language) is not in the file, the user clicks the command button and gets the "Enter Parameter Value" message box. If they hit cancel they then get my message box explaining the field is not present in the file. I would like to bypass the "Enter Parameter Value" and go straight to the message if the field is not found. Here is my code:
Private Sub LangCount_Click()
DoCmd.SetWarnings False
On Error GoTo Err_LangCount_Click
Dim stDocName As String
stDocName = "LanguageCount"
DoCmd.OpenQuery stDocName, acNormal, acEdit
Err_LangCount_Click:
MsgBox "No Language field found in Scrubbed file"
Exit_LangCount_Click:
Exit Sub
DoCmd.SetWarnings True
End Sub
You can attempt to open a recordset based on the query before you run the query:
Set rs = CurrentDb.QueryDefs("query1").OpenRecordset
This will go straight to the error coding if anything is wrong with the query.
Alternatively, if it is always the language field and always in the same table, you can:
sSQL = "select language from table1 where 1=2"
CurrentDb.OpenRecordset sSQL
This will also fail and go to your error coding, but if it does not fail, you will have a much smaller recordset, one with zero records.
You can easily enough get a list of fields in a table with ADO Schemas:
Dim cn As Object ''ADODB.Connection
Dim i As Integer, msg As String
Set cn = CurrentProject.Connection
Set rs = cn.OpenSchema(adSchemaColumns, Array(Null, Null, "Scrubbed"))
While Not rs.EOF
i = i + 1
msg = msg & rs!COLUMN_NAME & vbCrLf
rs.MoveNext
Wend
msg = "Fields: " & i & vbCrLf & msg
MsgBox msg
More info: http://support.microsoft.com/kb/186246
You have a command button named LangCount. It's click event has to deal with the possibility that a field named Language is not present in your Scrubbed table.
So then consider why a user should be able to click that command button when the Language field is not present. When the field is not present, you know the OpenQuery won't work (right?) ... so just disable the command button.
See if the following approach points you to something useful.
Private Sub Form_Load()
Me.LangCount.Enabled = FieldExists("Language", "Scrubbed")
End Sub
That could work if the structure of Scrubbed doesn't change after your form is opened. If the form also includes an option to revise Scrubbed structure, update LangCount.Enabled from that operation.
Here is a quick & dirty (minimally tested, no error handling) FieldExists() function to get you started.
Public Function FieldExists(ByVal pField As String, _
ByVal pTable As String) As Boolean
Dim blnReturn As Boolean
Dim db As DAO.Database
Dim fld As DAO.Field
Dim tdf As DAO.TableDef
Set db = CurrentDb
' next line will throw error #3265 (Item not found in this collection) '
' if table named by pTable does not exist in current database '
Set tdf = db.TableDefs(pTable)
'next line is not actually needed '
blnReturn = False
For Each fld In tdf.Fields
If fld.Name = pField Then
blnReturn = True
Exit For
End If
Next fld
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
FieldExists = blnReturn
End Function

VBA and Access Form Filter

I have this form in access, the purpose of it is to work as a front end of a table which can be edited through this form. Initially when it loads I display in the form data from a recordset with the following query:
SELECT * FROM DATA
I want to be able to filter the data on the recordset once the form is open. I tried the following VBA code to accomplish this:
Private Sub Filter_Click()
If (IsNull(Me.Find_Field) Or Me.Find_Field = "") Then
rs.Close
Set rs = db.OpenRecordset("Select * from DATA ORDER BY ID)
rs.MoveFirst
LoadData (True)
Exit Sub
End If
Set rs = db.OpenRecordset("Select * from DATA WHERE ID = " & Me.Find_Field)
rs.MoveFirst
LoadData (True) ' Function that loads the data into the form
Exit Sub
As you all can see, I reload the recordset with a new filtered query. Up to this point it works, the problems begin when I try to modify a record.
Originally, when the form loads the recordset data, I am able to edit the data and the edited data would show in the table (which is what I want). But after I apply my filter, my code gives me the Run-Time error '3027': Cannot Update. Databse or object is read-only.
I am pretty much using the same code over and over to reload data from the table and it never gave me a problem until I 'overwrote' the source of the recordset. Any idea how can I resolve this issue? Thanks
I would prefer to use a standard Access bound form because it's simpler than what you appear to be doing.
I can change the form's RecordSource from the click event of my cmdApplyFilter button.
Private Sub cmdApplyFilter_Click()
Dim strSql As String
If Len(Me.txtFind_Field & vbNullString) > 0 Then
strSql = "SELECT * FROM tblFoo WHERE id = " & _
Me.txtFind_Field & " ORDER BY id;"
Me.RecordSource = strSql
End If
End Sub
If you're concerned someone might save the form with the filtered RecordSource, you can make the form always open with the unfiltered version.
Private Sub Form_Open(Cancel As Integer)
Dim strSql As String
strSql = "SELECT * FROM tblFoo ORDER BY id;"
Me.RecordSource = strSql
End Sub