Showing table records in a report with different textboxes - vba

I have a table name is Table1 with 2 fields which are Name and Married_Status.
For Name includes Names of the employees and for the Married_Status includes Yes or No.
The Question is: Can I show them in a report by 2 ways? first when the status is Yes 2 textboxes appear but if the status in No 1 textboxes appears?
I use Access 2016

If I am understanding you correctly you want to hide the Married_Status column if it is no. However this answer covers hiding other columns if I am misunderstanding. In short, this is called conditional formatting and is done by highlighting the control-clicking the format tab- then clicking conditional formatting. However, access can only conditionally format the text color, font, and background of a control. Further the default control for a yes/no variable is a checkbox and the checkbox allows no conditional formatting.
There are two work-arounds. First you can make the Married_Status text box invisible in all cases:
base the report on a query and replace Married_Status with a Calculated variable like:
Married_Status: IIf([Table1].[Married_Status]=True,"Married",Null)
If we use a text box for Married_Status and make it transparent we get:
When Married_Status is Null and the Married_Status textbox is transparent nothing shows. Unfortunately a checkbox shows even when the value is null.
The second work-around requires you know a lot about the data in advance and should only be done if the boss insists. You can build the report using VBA. For my sample data I know I have one page of 4 cases so I can avoid the detail section which limits me to one control for every instance of Married_Status and put as many controls as I need in the Header:
Then in the load event use vba to set the controls:
Private Sub Report_Load()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Table1")
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
For i = 1 To 4
Me.Controls("Text" & i) = rs("EmployeeName")
If rs("Married_Status") = True Then
Me.Controls("Check" & i) = True
Else
Me.Controls("Check" & i).Visible = False
End If
rs.MoveNext
Next i
End If
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub

Related

MS Access VBA: Fetch data from a query which corresponds to an ID field from a selected row in a subform table

I'm completely new to VBA and MS Access!
I have a Subform within a form which contains data about items which all have an "Equipment ID" field.
Using data from a different table, I have a query to count the number of "faults" associated with each item. This Query also has the "Equipment ID" field.
I have a second form which contains text boxes, and can be accessed by a button. On the button click, the form opens up and data from the selected current row in the subform are passed into the text boxes. I have assigned the original data table to the form control source.
What I want to do:
I'm having trouble with the query. I have been trying to link the subform and the query, so that when the row on the sub form is selected, the "Equipment ID" is grabbed from that, and the "number of faults" in the Query can be found from its corresponding "Equipment ID".
Here is the code so far (and what I want to happen in comments):
Private Sub Button_Click()
Dim db As Database
Dim rs As DAO.Recordset
Dim EqIDfrm As String 'Equipment ID from the subform
'Open up the Faults Query
Set db = CurrentDb
Set rs = db.OpenRecordset("qryFaultTotal")
'open up the second form
DoCmd.OpenForm "SecondForm"
'Grab the "Year" from the selected row in the sub form and assign it to SelectYear. The text
'box value in the second form then becomes the SelectYear value.
SelectYear = [Forms]![Form1]![tblAsset Subform].[Form]![Year]
[Forms]![Form2]![txtYear] = SelectYear
' etc. for other fields
'grab the equipment ID from the subform and from the Query
EqIDfrm = [Forms]![Form1]![tblAsset Subform].[Form]![Equipment_ID]
EqIDqry = rs![Equipment_ID]
'<--- this seems to be part of the problem
'Lookup the Total number of faults from the FaultTotal Query, where the Equipment ID in the Query is
the same as the equipment ID on the subform from the selected row.
Fault = DLookup("[TotalFault]", "[FaultTotal]", "[EqIDqry] = " & [EqIDfrm] & "")
End Sub
When I use lookup I keep getting an error of some sort (type mismatch, run-time error), and I just can't figure it out. It doesn't seem to like the EqIDqry but I don't know why despite Googling. I feel like it should be very simple, but I understand I may have to do something totally different! Any advice would be appreciated :)

Populating a text box with some text depending on values of dropdowns selected in document

I am making a document in Microsoft Word 2016 and I would like this to be a form that a user will fill out (using Dropdown list content control)- from there I have assigned all of the items in the list with numbers for their values. I need to populate a text box with some words (determined by the sum of the values) and I am having trouble. Never used VBA- I don't even know if my first line is correct. I'm really not sure how to begin the document and how to populate the sum of all the dropdowns. I'm not using macros from another document, I just want to populate based upon what users select in the word document. I named my field with a tag on a text box that I want the text "account" "account 2" etc to appear in. Thanks!
Set myField = Selection.FormFields(1)
If myField.Type = wdFieldFormDropDown Then
Num = myField.DropDown.ListEntries.Count
If Num >= 75 Then
myField.Value = "Account 1"
End If
If Num > 50 Then
myField.Value = "Account 2"
End If
If Num <= 50 Then
myField.Value = "Account 3"
End If
End If
End Sub
If you plan to use Content Controls then FormField object in your code is not correct. Form fields are "legacy" - they're still quite useful, but it's a different part of the object model.
Content Controls are "embedded" in the document and have events to trigger code. That means you need to double-click the ThisDocument entry in the Project for the parent document in the VB Editor. Then select "Document" from the dropdown to the left of the Code Window and "ContentControlOnExit" from the dropdown on the right. That will insert the event stub in the code window for ThisDocument (see picture).
A Content Control event will trigger for all content controls in the document, which means you need to distinguish which content control triggered it. The event passes in a ContentControl object which can be tested for this purpose, usually using Select Case.
The sample code shows how to do this, how to get the count of the ListEntries, how to select a specific content control by its title (or by its tag) and how to write content to the content control. (Since what you want to do with Num in your code, above, is not clear to me I don't try to include that. But it looks like here, as well, you could use Select Case.)
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _
Cancel As Boolean)
Dim cc As Word.ContentControl
Dim doc As Word.Document
Dim countListEntries As Long
Set doc = ContentControl.Parent
Select Case ContentControl.Title
Case "SelectAccount"
countListEntries = ContentControl.DropdownListEntries.Count
Set cc = doc.SelectContentControlsByTitle("Account").Item(1)
'Set cc =doc.SelectContentControlsByTag("Account").Item(1)
cc.Range.Text = ContentControl.Range.Text & " " & countListEntries
Case Else
End Select
End Sub

display searched data in listbox in vba

I am new to VBA coding..
help me in this situation..
I have a table like in sheet 1
Data table
& the user-form is like
User form
I need to display the searched data in this list-box...my logic which i have tried...
1) a variable which holds the text-box value
2) 1st tried with advanced filter but its not working
3) then tried with find function it also shows error..
I have tried but it does not display in list-box...it is my first working with list-box...thanks in advanced....
The details might well vary between Access and Excel, and the version of those tools ... I happened to use Access 2000 for this example.
In case you're not sure how to see what an icon is named: float the mouse cursor over it.
I opened the form in design view
I activated a toolbar that had the "Toolbox" icon
I selected "List box"
I clicked on the form and dragged a box shape. This made a caption box containing "List1:" and also a list box
I changed the caption to whatever matches the table I plan to use, which is "tblDomainName" hence "Domain Name:"
I opened up the properties for the list box and clicked in the "Row Source" area.
I typed "SELECT DomainName FROM tblDomainName ORDER BY DomainName" based on the table planned to use, so if your table were named "Stuff" then you'd type what's inside the double-quotes, here: "SELECT [Name] FROM Stuff ORDER BY [Name]" ... notice the square brackets in case "Name" is a reserved word that might cause confusion otherwise.
I changed to form "view" mode and clicked through the various values. They matched what's in my table, and they were sorted besides. Yay!
So, the above gets the list box basically working and gets you past your first hurdle ... as I understand it to be.
What's next? As to how you use that list box, and the selected value, to your benefit .... that depends on what the big picture is, so feel free to elaborate.
Does this help?
~Tanya
can you please show your codes you have tried? I'm sorry if I can't just comment on your question coz I'm still lacking in reputation. Thanks!
Please Try this code below:
Private Sub cmdSearch_Click()
Dim ws As Worksheet
Dim numRow As Integer
Dim found As Boolean
Set ws = ThisWorkbook.Worksheets("display")
For numRow = 1 To (ws.Range("A" & ws.Rows.Count).End(xlUp).Row)
If nameTxtBox.Value = ws.Range("A" & numRow).Text Then
nameList.AddItem (ws.Range("A" & numRow).Value)
prodList.AddItem (ws.Range("B" & numRow).Value)
saleList.AddItem (ws.Range("C" & numRow).Value)
found = True
Exit For
End If
Next numRow
If found = False Then
MsgBox "No Match Found!", vbCritical
nameList.Clear
prodList.Clear
saleList.Clear
End If
End Sub
userForm screen shot
Spread Sheet Screenshot:
hope this is what you want to do!
Thanks!

Access Calculate Next Value (lookup value}?

I need to get a value from a textbox in a report's detail section which will give me multiple values. I need to get each of those values into VB to do some calculations... I can pull a value from forms with ChildID = Forms!FRM_Child!ChildID.Value, but when I put
Private Sub Report_Open(Cancel As Integer)
Dim ChildID as Integer
ChildID = Reports!RPT_Due_Date!ChildID.Value
End Sub
it crashes and says "Run-time error '2424': The expression you entered has a field, control, or property name that Microsoft Access can't find."
I've checked and double checked the names. The thing I figure is that somehow because it's in the detail section with multiple values it crashes. Any ideas?
ChildID Last_Asmt_Type Last_Asmt_Date Next_Asmt_Type Next_Asmt_Date
1 Initial Evaluation 1/5/15 Periodic Review 5/5/15
2 Periodic Review 2/5/15 Annual Review 6/1/15
3 Annual Review 3/5/15 Periodic Review 7/1/15
What I want to do is get the Last_Asmt_Type and then with if/then rules select the Next_Asmt_Type ie If Last_Asmt_Type is Periodic Then Next_Asmt_Type is Annual....
How would I do this with a lookup value?
In Report_Open(), the textbox exists as control, but it has no value yet.
Your code would work in Report_Load(), but as you already know, it would be pointless because you would only get the first value.
If you want to read all values, don't try to read them from the report textbox, open a recordset on the report's data source. Like this:
Dim RS As Recordset
Set RS = CurrentDb.OpenRecordset(Me.RecordSource)
Do While Not RS.EOF
Debug.Print RS!MMI
RS.MoveNext
Loop
RS.Close
But:
Most probably there is an entirely different and better way to do what you want. What kind of calculations are you doing?

Customizing an access query based on values of various checkboxes

I'm new to access, and I need to selectively query a database based on a set of checkboxes. For example, If a checkbox called basketball is checked, I'll want to find all records that have that in their Name field. If basketball and baseball are checked, I'll want to find records for both basketball and baseball. The current way we have of doing this is ugly and inefficient, and I'm thinking that this is a fairly common problem to have, so there must be a better way of solving it. I've seen similar things online, but these deal with only one checkbox (not 10 or so like in our form) and they simply aren't very helpful.
Thanks
I'll make a few assumptions, here. I'll assume you have 4 sports; Baseball, Basketball, Football and Hockey. You can add more if you like.
I'll assume you have 4 checkboxes; BaseballCheck, BasketballCheck, FootballCheck and HockeyCheck.
I'll assume you have a table called MyTable, with a field called Sport.
What you can do is add a button to your form. Call it btnSubmit. Add this VBA to your button:
Dim db as Database
Dim rec as Recordset
Dim MySQL as String
Set db = CurrentDB
MySQL = "SELECT * FROM MyTable WHERE 1 = 1"
If BaseballCheck = True then
MySQL = MySQL & " AND Sport = 'Baseball'"
EndIf
If HockeyCheck = True then
MySQL = MySQL & " AND Sport = 'Hockey'"
EndIf
If BasketballCheck = True then
MySQL = MySQL & " AND Sport = 'Basketball'"
EndIf
Etc...
Set rec = db.OpenRecordset(MySQL)
Instead of that last statement, you can use CreateQuerydef to create a permanent query that you can then use as the basis for a report. However, you would have to add some code at the beginning to delete that querydef if it exists, otherwise it will throw an error.
If you want something a little more elegant (and one that will allow for easier scalability) you could always loop through all the checkboxes on your form and dump the sports into an array, and then use that array as the subject of a "WHERE Sport IN (...)" statement.
As no reference information is provided, i use the following for this example;
Formname = Form1
Tablename = test
Checkfieldname = BaseballCheck
In the form property sheet, add the following vba for the BaseBallCheck, this will requery the form after the check has been enabled/disabled.
Private Sub BaseballCheck_AfterUpdate()
Me.Requery
End Sub
Then in the form Recordsource add the following
SELECT test.Baseball
FROM test
WHERE (((test.Baseball)=[forms]![Form1]![BaseballCheck]));
Now when the form refreshes only the values are shown where Baseball = checked or unchecked.