Access - Change fields in table automatically, if a field changes - sql

Lets say I got a table with an id, pre- and lastname. I made them work as comboboxes in the table. Now if I change 1 field (lets say the id) with the combobox I want that all the other stuff is changed too (the pre and lastname). How to achieve that (with a macro or vba, or is it easier)?

I solved it. I made a sub formular. Then i managed to dropdown the fields I wanted to. Copying the same table for finding the names ids...
And then i created an event for after update:
Private Sub PartnerIdServiceWorker_AfterUpdate()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("SELECT * FROM HTB WHERE PartnerIdServiceWorker = " & PartnerIdServiceWorker)
Do While Not rst.EOF
Me.AnredeMitarbeiter = rst!AnredeMitarbeiter
Me.VornameMitarbeiter = rst!VornameMitarbeiter
Me.NachnameMitarbeiter = rst!NachnameMitarbeiter
Exit Do
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Now I'm able to change the fields in the table and the other values do also change.

Related

Need top3 records in MS Access

I have to create a text box in MS Access where users are able to see the top 3 records of a particular result set. So even if the query results in 5 records I only want it to display the top 3 records as three textboxes (sometimes the result may also be 1,2 or 0 records).
I took the easy way out and created a new subform which was connected to the parent form using master/child field. The textbox was placed in the details part of the subform and as a recordsource of the subfrom used the following query:
Select top 3 tbl1.column1, tbl1.column2
from tbl1
column1 is the control source for the textbox and column2 is the column I have used for master/child link.
Now the catch is that the query works fine when I use it without top 3. But when I use top 3 the textbox suddenly disappears and the subform is completely blank.
I am not able to identify the cause of the error. My guess is that it has something to do with type of the subform. Not sure.
Is there any other way I can have a text box whose number can vary on the basis of the results?(but limiting the resultset to 3)
Appreciate the help.
Textbox are not meant to hold more than 1 value.
You are trying to assign three results of 2 columns to one textbox(No can do).
Use listbox to populate as you are doing, assigning the query you just wrote in the rowsource of the list(no subforms needed). This way users will see the three records.
You could use a textbox in order to accomplish what you are trying to do. But will require some VBA coding to accomplish this.
Public function CombineValuesForTextBox() as string
Dim rst as dao.recordset
Dim strSQL as string
strSQL = "SELECT TOP 3 tbl1.Column1 as field1, tbl1.Column2 as field2 " & _
"FROM tbl1;"
set rst = currentdb.openrecordset(strsql)
if rst.recordcount = 0 then 'Checks if the recordset has records or not
CombineValuesForTextBox = "No records found"
goto EndCode 'Or replace with what actions to take if no records are found
else
rst.movelast 'Forces the recordset to fully load
rst.movefirst
do while not rst.eof
if CombineValuesForTextBox = "" or CombineValuesForTextBox = empty then
CombineValuesForTextBox = rst![field1] & " - " & rst![Field2]
else
CombineValuesForTextBox = CombineValuesForTextBox & vbcrlf & _
rst![field1] & " - " & rst![Field2]
end if
Loop
end if
rst.close
set rst = nothing
EndCode:
if not rst is nothing then
rst.close
set rst = nothing
end if
end function
Then on your form put in the code (be sure the textbox is unbound...)
me.textbox = CombineValuesForTextBox

How to add check boxes to a form based on columns in table in Access?

I have a form in Access that allows a user to select a table from a combo box that lists all of the tables using VBA. Based on what table the user selects, I want a set of check boxes to be added to the form. Each check box would represent a column in the chosen table. I have a VBA function that will work with the columns that are chosen through the form after a button is pressed.
How would I make the check boxes appear after the user has chosen a table? I want this form to be applicable to tables that would be added in the future as well so I won't know the number of columns in advance. I can get check boxes to appear dynamically in a Userform but I've heard that they aren't commonly used in Access. I have also heard that there is a limit for the amount of controls that can be added to a form in its lifetime. Is there anyway of renaming controls so that I don't hit this limit?
This is the code that I use to populate the combo box:
Private Sub Form_Load()
Dim tbl As DAO.TableDef
Dim db As Database
Set db = CurrentDb
With Me![TableName]
For Each tbl In db.TableDefs
If Not (tbl.name Like "MSys*" Or tbl.name Like "~*") Then
.AddItem tbl.name
End If
Next
End With
End Sub
This is example code that can generate the check boxes in a Userform:
Private Sub RetrieveColumns_Click()
Dim TableName As String
Dim MethodName As String
Dim tdf As DAO.TableDef
Dim rs As Recordset
Dim fld As Field
Dim chkBox As MSForms.CheckBox
TableName = Me![TableName]
Set tdf = dbs.CreateTableDef(TableName)
Set rs = dbs.OpenRecordset(TableName)
With rs
For i = 0 To .Fields.Count - 1
Set chkBox = Me.Controls("Forms.checkbox.1", "CheckBox_" & i)
chkBox.Caption = .Fields(i).name
chkBox.Left = 5
chkBox.Top = 5 + ((i - 1) * 20)
Next i
End With
End Sub
The best solution would be a continuous form / datasheet that shows all table column names with an adjacent checkbox.
Create a table with ColumnName (Text) and Checked (Yes/No, Default No).
Then when a table is selected:
delete * from this table,
In your .Fields loop, insert all column names into this table,
and show the table as subform (or have the table selection combobox in the form header).
With this, you don't need any dynamic controls.
Alternatively, for a truly simple solution, use a multi-select listbox.
A listbox has the slightly obscure RowSourceType Field List.
The data is a list of field names from a table, query, or SQL statement specified by the RowSource setting.
So all you'd need is to set the RowSource property to the selected table name.

Display multiple yes/no fields in single line

i Have a table Tools where there are 15 yes/no fields. User checks which tools were used in an event. Could be one or more, or none. There are other fields in the table, but all the relevant field names start with tblTool
In report I'd like to display the tools in single line, Something like 'Tools used: hammer, chisel...'
My current solution for this is a bunch of if statements that check each item and add it to the variable if it's positive. My question is this, is there a simpler way? some kind of a loop that would check all the field names in a certain table that start with the same string?
might have solved this
txt = ""
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("Select * from ops where opID = " & Me.opID)
Dim fld As DAO.Field
For Each fld In rs1.Fields
If Left(fld.Name, 5) = "opImp" Then
If fld = True Then
txt = txt & fld.Name
End If
End If
Next
Set fld = Nothing

Query every table in an Access Database?

All tables in a certain database have the exact columns, so I'm wondering if there is a way I can query all of them at once for a specific few columns that I know every table will have. The reason I want to do this is that the number of tables in the database will constantly be growing, and I don't want to have to every day go and change my query to accommodate the names of the new tables.
Help is appreciated as always
In that case, try ADO:
Function ListTablesContainingField(SelectFieldName) As String
'Tables returned will include linked tables
'I have added a little error coding. I don't normally do that
'for examples, so don't read anything into it :)
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTempList As String
On Error GoTo Error_Trap
Set cn = CurrentProject.Connection
'Get names of all tables that have a column called <SelectFieldName>
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
'List the tables that have been selected
While Not rs.EOF
'Exclude MS system tables
If Left(rs!Table_Name, 4) <> "MSys" Then
strTempList = strTempList & "," & rs!Table_Name
End If
rs.MoveNext
Wend
ListTablesContainingField = Mid(strTempList, 2)
Exit_Here:
rs.Close
Set cn = Nothing
Exit Function
Error_Trap:
MsgBox Err.Description
Resume Exit_Here
End Function
From: http://wiki.lessthandot.com/index.php/ADO_Schemas
You might like to consider a table of tables, if you have not already got one, that lists the linked Excel tables and holds details of archive dates etc, because you will run into limits at some stage.

VBA to Trim all Cells in an Access Table

I'm relatively experienced with Object oriented programming, but this is my first time ever working in Office with VBA and I'm entirely stumped by the syntax. I've been doing some searching and messing with it for the past hour or so, but have been trouble actually getting a macro that runs successfully and does what I need.
I'm attempting to loop through every cell in an Access table and apply the Trim function to the contents of that cell and, as a bonus, I'd like to remove all extra spaces in the string (if any). I.e. " Trim this__string " would simply become "Trim this string" (I used the underscore there to represent individual, multiple spaces since StackOverflow didn't want to show my multiple spaces).
Any code example of doing something like this, or at least something to get me close and then I can tinker with it, would be greatly appreciated. Thanks!
You can remove leading and trailing spaces with the Trim() function in a query.
UPDATE YourTable
SET text_field = Trim(text_field);
If you will be doing this from within an Access session, you could use Replace() to replace a sequence of two spaces with a single space.
UPDATE YourTable
SET text_field = Replace(text_field, ' ', ' ');
However you may need to run that Replace() query more than once to get all the contiguous space characters down to only one.
You could also do a regular expression-based replacement with a user-defined function. I don't know if that's worth the effort, though. And a user-defined function is also only available from within an Access application session.
I overlooked the "every cell in a table" aspect. That makes this more challenging and I don't think you can solve it with a standard macro or query. You can however use VBA code to examine the TableDef, and iterate through its fields ... then call your Trim and/or Replace operations on any of those fields whose data type is text or memo.
Here's a rough code outline to identify which fields of a given table are text type.
Public Sub FindTextFields(ByVal WhichTable As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set db = CurrentDb
Set tdf = db.TableDefs(WhichTable)
For Each fld In tdf.Fields
If fld.Type = dbText Or fld.Type = dbMemo Then
Debug.Print "Do something with " & fld.Name
End If
Next
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub
Option Compare Database
Private Sub Command3_Click()
Call findField(Text1.Value)
End Sub
Public Function findField(p_myFieldName)
Dim db As Database, _
tb As TableDef, _
fd As Field
'''''''''Clearing the contents of the table
DoCmd.RunSQL "delete * from Field_Match_Found"
Set db = CurrentDb
For Each tb In db.TableDefs
For Each fd In tb.Fields
If fd.Name = p_myFieldName Then
strsql = "INSERT INTO Field_Match_Found Values (""" & tb.Name & """, """ & fd.Name & """)"
DoCmd.RunSQL strsql
End If
Next fd
Next tb
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
If DCount("Account_number", "Field_Match_Found") = 0 Then
MsgBox ("No match was found")
Else
MsgBox ("Check Table Field_Match_Found for your output")
''''''''''making textbox blank for next time
Text1.Value = ""
End Function