I'm trying to build a database with MS Access. I have two tables- StockFrames and Projects, and I have a form- FrameCheckOut. On the form I have a FrameID field (where we will type in a frame id number or scan its barcode) and a ProjectName field, with a drop down of project names from the Projects table. I also have a button- Assign Frame. I want the button to update the StockFrames table with the projectID number so that I can know whether or not a frame is currently in use (or "checked out") to a project.
I have tried assigning this code to the button On Click:
UPDATE StockFrames
SET StockFrames.projectID = [SELECT Projects.projectID
FROM Projects WHERE Projects.projectName LIKE projectName]
WHERE frameID = frameID;
.. but that code contains invalid syntax. I am very new to Access and coding and I would really appreciate some help if anyone is willing.
Include key field in combobox (column can be hidden) RowSource. Value of combobox will be ID but users see and type name. Combobox properties:
RowSource: SELECT ProjectID, ProjectName FROM Projects ORDER BY ProjectName;
BoundColumn: 1
ColumnCount: 2
ColumnWidths: 0";2"
ControlSource: leave blank if control is used to enter search criteria, otherwise field you want to save into
If form is bound to StockFrames, an UPDATE action is not needed. Find record for specific FrameID and simply select project from combobox.
If you prefer to use UPDATE, then have UNBOUND comboboxes for Frames and Projects designed as described above. Example VBA:
Private Sub AssignFrame_Click()
CurrentDb.Execute "UPDATE StockFrames SET ProjectID = " & Me.cbxProject & _
" WHERE FrameID = " & Me.cbxFrame
End Sub
Related
I've been curious as to how to accomplish something like this:
tblProject
id
1
2
tblSample
id projectID sampleNumber
1 1 1
2 1 2
3 1 3
tblTests
id testName
1 test1
2 test2
3 test3
tblTestResults
id testID projectID sampleID testResults
1 1 1 1
2 2 1 1
3 3 1 1
I want to output the following into a datasheet:
projectID sampleID testID test1 test2 test3
1 1 1 entry entry entry
1 1 2 entry entry entry
1 1 3 entry entry entry
Test1, Test2, and Test3 are names from tblTests. Is there a way to automatically update the entered items underneath the test name columns? Pivoting will not allow edits. The solutions I came up with are workarounds:
1) Output the pivot into a listbox, double clicking it will load a form that has the tests.
2) Use a gridview. Load the headers: projectID, sampleID, and test names. In an array, keep track of the test name column and which testresult id it belongs to. AFter update, manually update the field.
Is there a better method?
Thank you
Starting with Access 2002, Microsoft upgraded Access forms to substantially improve their ability to present data in a pivot-table format. These capabilities build on features initially introduced in Access 2000 for Office Web Components.
Programmatically creating a pivot table
Before starting to program pivot tables for Access forms, you need a reference to the Office Web Components library (owc10.dll). In Access 2002/2003, the library file is available in the \Program Files\Common Files\Microsoft Shared\Web Components\10 path. In Access 2002, the Microsoft Office XP Web Components item doesn't appear in the References dialog box. Therefore, you must know the path to the library file (owc10.dll) so that you can browse to it when specifying a reference.
Creating a pivot table programmatically for an Access form can require several steps:
First, you need to create a form that will hold your pivot table. You can do this with the CreateForm method.
Next, you'll typically want to change the default name assigned to the form by the CreateForm method. This practice lets your Access form name reflect its role in an application.
Finally, you need to configure the active view for a pivot table on an Access form so that it organizes the data to display into appropriate row, column, and filter axes. You do this by assigning column names from an Access table or query to axes for the active view of a pivot table.
The Office Web Components object model uses terms such as RowAxis and ColumnAxis to designate axes for an active view. Any data to be organized belongs on the DataAxis of an active view. You can designate multiple columns of data as belonging to row, column, filter, and data axes.
Creating a pivot table based on a table
The Access file with the samples for this article is available to download here. The file contains a form, named frmPVTDesigner, with five buttons. The top button, labeled Make Orders PivotTable, creates a simple pivot table based on the Orders table imported from the Northwind.mdb file. The pivot table (see the left pane in this [image]2) categorizes OrderID by ShipCountry. The code behind the button saves the pivot table in the pvtOrders form. After invoking the click event procedure for the button, you need to delete the pvtOrders form before you can re-run the click event procedure (or change the code in the event procedure so that it saves the new form with a different name).
With a pivot table like the one in the left pane this [image]2, an analyst can display a count of the number of orders for each ShipCountry. The right panel in this [image]2 shows that there are 16 orders with a ShipCountry column value of "Argentina". Users can generate this subtotal by right-clicking the OrderID column heading in the pivot table and choosing AutoCalc > Count. In addition, by clicking the Hide Details button on the PivotTable toolbar, users can elect to suppress the display of the individual OrderID values so that just the counts appear.
By calling three other procedures, the Click event procedure for the top button creates a form for the pivot table, assigns the custom name pvtOrders to the form, and configures the pivot table. The application uses a couple of module-level variables, strFormName and strRecordSource:
Sub CreatePivot()
Dim strFormName As String
Dim strRecordSource As String
Private Sub cmdOrdersPivotTable_Click()
Dim strDefaultName As String
strRecordSource = "Orders"
strDefaultName = CreatePivotTable
strFormName = "pvtOrders"
If (AssignPivotTableName(strDefaultName, _
strFormName)) = False Then
Exit Sub
End If
ConfigureOrdersPivotTable
End Sub
The CreatePivotTable function procedure called from this code creates a new form with a RecordSource property setting equal to strRecordSource, one of the two module-level variables. You must assign a record source for a form before attempting to configure a pivot table on the form. The CreatePivotTable procedure assigns a value to the form's DefaultView property so that the form opens with a PivotTable view when a user opens the form from the Database window. This DefaultView setting doesn't impact how the OpenForm method of the DoCmd object opens the form.
The CreatePivotTable routine returns to the cmdOrdersPivotTable_Click routine the name of the new form. This name has the format Formn, where n is an integer value. After CreatePivotTable saves the form's settings and closes the form, cmdOrdersPivotTable_Click passes the default form name and a custom form name to AssignPivotTableName, which is another one of my functions. This function assigns a new custom name to the form for the pivot table unless the custom form name already belongs to another form in the database file. A For...Each loop searches through the members of the AllForms collection to determine whether another existing form already has the name for the new form. When the new custom form name already belongs to an existing form, the function procedure deletes the form created by CreatePivotTable and returns a value of False to indicate that it didn't rename the form. In this situation, cmdOrdersPivotTable_Click terminates the application. Otherwise, the AssignPivotTableName procedure successfully renames the new form and returns a value of True to cmdOrdersPivotTable_Click:
Function CreatePivotTable() As String
Const acFormPivotTable = 3
Dim frm1 As Access.Form
Set frm1 = CreateForm
frm1.DefaultView = acFormPivotTable
frm1.RecordSource = strRecordSource
CreatePivotTable = frm1.Name
DoCmd.Close acForm, CreatePivotTable, _
acSaveYes
End Function
Function AssignPivotTableName _
(strDefaultName As String, _
strFormName As String) As Boolean
Dim acc1 As AccessObject
AssignPivotTableName = True
For Each acc1 In CurrentProject.AllForms
If acc1.Name = strFormName Then
MsgBox "Choose a form name other " & _
"than '" & strFormName & "' that " & _
"does not match an existing form."
AssignPivotTableName = False
DoCmd.DeleteObject acForm, strDefaultName
Exit Function
End If
Next acc1
DoCmd.Rename strFormName, acForm, _
strDefaultName
End Function
After the application creates a form and assigns a custom name to it, the ConfigureOrdersPivotTable procedure assigns columns from the form's RecordSource setting to axes of the active view for the pivot table on the form. CreatePivotTable and AssignPivotTableName can be reused when creating any form for a pivot table, but the procedure for configuring a pivot table will typically be unique for each pivot table.
The configuration procedure initially opens the form for which it specifies a pivot table. Next, it uses a With...End With statement to point at the ActiveView object for the PivotTable object on the form. Inside the With...End With statement, the procedure successively assigns columns (in this case, ShipCountry and OrderID) to a PivotFieldset object (fst1). The code inside the With...End With statement inserts the PivotFieldset in an axis for the ActiveView object. ConfigureOrdersPivotTable assigns the PivotFieldset with the ShipCountry column to the RowAxis property of the ActiveView and the PivotFieldset with the OrderID column to the DataAxis property of the ActiveView:
Sub ConfigureOrdersPivotTable()
Dim fst1 as PivotFieldset
'Open form in PivotTable view and set
'a reference to the form
DoCmd.OpenForm strFormName, acFormPivotTable
Set frm1 = Forms.Item(strFormName)
'Set PivotTable fieldsets
With frm1.PivotTable.ActiveView
Set fst1 = .FieldSets("ShipCountry")
.RowAxis.InsertFieldSet fst1
Set fst1 = .FieldSets("OrderID")
.DataAxis.InsertFieldSet fst1
End With
'Close form with its PivotTable view
DoCmd.Close acForm, frm1.Name, acSaveYes
End Sub
See:
More information on this example is available at the Source.
MSDN: Form.PivotTable Property (Access)
Stack Overflow: Edit pivot table contents in Access
I prefer in such kind cases to use temporary tables. Copy pivot data to temp table and return back edited data after clicking Save button, few simple queries will do the job
I am creating a small Access DB for our Data Entry guys. Our main DB is mysql but due to ease of use we are creating an Access DB to make it easier for them to enter the Data. I have done most of it but am stuck with this problem (which I know how to solve in mysql+php) Please pardon my ignorance, but I have just started using MS Access.
I have two tables - ClientPhones and sales. The ClientPhones table has phone, clientid fields. sales table has salesid, clientid, date, etc fields.
I also have a Form which has all relevant fields for the sales table. I want to add a new field, phone_no in that form. When a user inputs the number and on focus lose event, I was access to run a query on the clients table to see if the phone number exists in any of the 3 phone number fields. If it finds a client with that phone number, the client ID should be populated, else a new form to input the client details should be shown.
Is this possible with MS access or am I doing this incorrectly?
Use the text box's After Update event to retrieve the clientid which matches the phone number the user entered.
If a clientid is found, store it in the text box which is bound to clientid.
If no match is found, ask whether the user wants to add a new client, and open that form if they respond yes.
This code outline assumes txtSearchPhone is the name of the text box where the user enters the target phone number, and txtClientId is the name of the text box where you want to store clientid.
Private Sub txtSearchPhone_AfterUpdate()
Dim varClientId As Variant
Dim strCriteria As String
strCriteria = "[phone]='" & Me.txtSearchPhone.Value & "'"
Debug.Print strCriteria '<-- inspect this in Immediate window; Ctrl+g will take you there
varClientId = DLookup("clientid", "ClientPhones", strCriteria)
If IsNull(varClientId) Then
If MsgBox("Add new user?", vbYesNo) = vbYes Then
'DoCmd.OpenForm ... (see Access help topic)
End If
Else
Me.txtClientId.Value = varClientId
End If
End Sub
Make sure the text in txtSearchPhone does not include a single quote character (') because the DLookup will break if it does. You can use the text box's Validation Rule and/or Before Update event to make sure a single quote is not present.
I have a simple ms access db with the following tables:
Patient
ID
Name
Medication
ID
Name
PatientMedication
ID
PatientID
MedicationID
This third table is a many to many table between Patient and Medication - recording what medications are taken by each patient. I want to create a form that populates this table by allowing me to select a patient and a medication, and storing a new row to the PatientMedication table.
I've gotten as far as creating the form with the dropdowns, and added a button to save the selected rows to the db, but don't know how to make the button do the insert. Do I have to write some VB code for the button? Do I even need a button? It seems that this is pretty trivial and I should be able to do it through some property of the form. Or is there a simpler way of going about this?
Any help would be appreciated.
You can actually handle it in several different ways. Below are a couple of options.
Option 1:
Set the Record Source property of the form PatientMedication. Set the dropdowns Control Source to PatientID and MedicationID. Then make sure that the required property of PatientID and MedicationID in the PatientMedication table is set to Yes. Then when a user selects a value for the drop downs the record will be added to the database. This assumes that the ID fields data type is set as AutoNumber.
Option 2:
Don't set the Record Source property of the form to PatientMedication. Don't set the dropdowns Control Source, leave them unbound. Set the MedicationID dropdown's Name property to txtMedicationID. Set the PatientID dropdown's Name property to txtPatientID. Set the command buttons Name property to cmdInsertRecord. Use the following code for the On Click event of the button:
Private Sub cmdInsertRecord_Click()
If (VBA.Strings.Len(txtPatientID & "") = 0) Then
MsgBox "You must specify a Patient ID before adding the record.", , "ERROR: Missing Information"
Exit Sub
End If
If (VBA.Strings.Len(txtMedicationID & "") = 0) Then
MsgBox "You must specify a Medication ID before adding the record.", , "ERROR: Missing Information"
Exit Sub
End If
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO PatientMedication (PatientID, MedicationID) Values " & _
"('" & txtPatientID & "', '" & txtMedicationID & "')"
DoCmd.SetWarnings True
End Sub
So I have this Access 2010 database into which users must login. The username they use is saved as a global variable. I then have a form which updates a table when they enter data and click a "save" button. I am trying to set one of the comboboxes (user) that is currently linked to a column in the table to be filtered on the global variable so that each person can only enter data under their own username. Is this possible? Does anyody know how to code this? I'm a complete newbie to Access and VBA and would appreciate any help
Greets
Me
In the form_load() function of that form you should fill the combobox with the global variable. To be sure they can't edit you should disable the combobox as well.
Private Sub Form_Load()
Me.myComboBoxName = gMyGlobalVariableName
Me.myComboBoxName.enabled = false
End Sub
However I'm assuming that the combobox has two columns (id and username) of which the first one is hidden and the primary key of some table where you store all the usernames. The gMyGlobalVariableName should have stored the id, not the username itself.
You can set the row source of the combo in the load event of the form to include only the relevant rows.
Me.TheCombo.RowSource = _
"SELECT UserColumn, Etc FROM TheTable WHERE UserColumn ='" _
& TheVariable & "'"
You may also wish to ensure that the form only contains the relevant records, however, the fact that you have a save button, suggests an unbound form. In Access, save buttons are largely redundant because the default is to save a record and stopping saves is the difficult bit.
I wonder why you do not use their windows log-in user name?
My Goal:
A form field (in MS Access) that is has some drop down choices. If the wanted value isn't in the lookup table, the user should be able to add it by typing it in.
Let's suppose the lookup table has rows: A, B, C, D. The user wants "E" which doesn't exist yet. Ideally they'd "override" and type in "E", which would then be added to the lookup table for future entries.
My google-fu has failed on this. Is there a term for this that I should be using? What are some good approaches? (I've been playing with combo-box and its wizard so far).
Thank you for any suggestions!
Aha, solved my own here:
http://allenbrowne.com/ser-27-01.html
Access 2007
To use the new properties in Access
2007:
Open your form in design view.
Right-click the combo, and choose Properties.
On the Data tab of the Properties box, set Allow Value List
Edits to Yes, and List Items Edit
Form to the name of the form to use
for adding items to the list.
When you are using this form, you can
now right-click the combo, and choose
Edit List Items.
There is also advice for older versions of Access.
You can try the following code:
Private Sub Combo33_NotInList(NewData As String, Response As Integer)
Dim strSql As String
If MsgBox(NewData & " not in list, add?", _
vbYesNo + vbQuestion) = vbYes Then
strSql = "insert into tblStudents (name) values(" & NewData & ")"
CurrentDb.Execute strSql
Response = acDataErrAdded
End If
End Sub
Note I used a table name of Students, and field name of Sname. So, just
change the table name, and the field to whatever you used.