Display multiple yes/no fields in single line - vba

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

Related

working with recordset on vba and access , how can I copy the last record and change a field of it

I have my source data in a table call "MyData" where I can see how many products I have, and what type of product they are.
if the product is product type A I create only one compensation rule. However, if the product it is type B, I need to create two compensation rules.
I use more or less the following algorythm
rsrule=db.OpenRecordset("Rules", dbOpenTable)
Do While Not rsdd.EOF
rsrule.AddNew
Do stuff
Detect the type of the product
type="B"
flag= true
rsrule.Update
now I want to add the same rule I have just added and change only one field rsrule![compensation percentage]=0.25
rsdd.MoveNext
Loop
Could anyone point me in the right direction to accomplish this?
Thank you very much
This looks like you have a 1 to many relationship between products and compensation rules. Each product can have many compensation rules. So structure the database accordingly:
The products table assigns 1 ProductID to each product in Stock. the ProductTypes and CompensationRuleTypes tables have been added so the database can expand to handle new products and compensation rules. The MyDataTable has no additional information so replace it with a form if the end user needs to do things like adding products and replace it with a report if the end user only needs to see the product counts.
Next it looks like you want vba code which fills the ProductCompensationRules table for all products. This code also checks to see if the appropriate rules have already been added and skips them in that case:
Private Sub FillCompensationRulesTableUsingVBA()
Dim rsProducts As dao.Recordset
Set rsProducts = CurrentDb.OpenRecordset("Products", dbOpenDynaset)
Dim rsProductsCompensationRules As dao.Recordset
Set rsProductsCompensationRules = CurrentDb.OpenRecordset("ProductCompensationRules", dbOpenDynaset)
rsProducts.MoveFirst
Do While Not rsProducts.EOF 'loop through products and add compensation rule 2 for all products and compensation rule 1 for producttype 2
If IsNull(DLookup("ProductID", "ProductCompensationRules", "ProductID = " & rsProducts!ProductID & " AND CompensationRuleID = 2")) Then
With rsProductsCompensationRules
.AddNew
!ProductID = rsProducts!ProductID
!CompensationRuleID = 2
.Update
End With
End If
If rsProducts!ProductTypeID = 2 Then
If IsNull(DLookup("ProductID", "ProductCompensationRules", "ProductID = " & rsProducts!ProductID & " AND CompensationRuleID = 1")) Then
With rsProductsCompensationRules
.AddNew
!ProductID = rsProducts!ProductID
!CompensationRuleID = 1
.Update
End With
End If
End If
rsProducts.MoveNext
Loop
'clean up
rsProducts.Close
rsProductsCompensationRules.Close
Set rsProducts = Nothing
Set rsProductsCompensationRules = Nothing
End Sub

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

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

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.

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

Delete record based on text found in a field (

I normally do most of this work in Excel 2007, but I do not think excel is the right tool for managing the data that I need to process. So I am trying to convert an excel spreadsheet to an Access 2007 db which I can do with no problem, but before doing anything to the spreadsheet I go through the process of cleaning up the data in it in order to use the resulting information. In excel I use a macro such as the following
Sub deletedExceptions_row()
Dim i As Long
Dim ws As Worksheet
On Error GoTo whoa
Set ws = Sheets("data")
With ws
For i = .Cells.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
If .Cells(i, 3) = "" Or _
VBA.Left(.Cells(i, 3), 4) = "511-" Or _
VBA.Left(.Cells(i, 3), 5) = "CARL-" Then
.Rows(i).Delete
End If
Next i
End With
Exit Sub
whoa:
MsgBox "Value of i is " & i
End Sub
to remove unnecessary records in the spreadsheet how would I accomplish the same thing in Access 2007.
The macro is looking for particular parts or rather the first few characters of the record's 3rd field in order to determine if the whole record needs to be removed (ex. 511-QWTY-SVP or CARL-52589-00). In all there about 180 such character types that affect 1000's of rows that need to be removed from the spreadsheet, but I would like to replicate that same process in Access 2007, but do not know how.
Thank you all for your assistance with this problem
Within Access you can execute a DELETE statement to discard rows where the value in a field is an empty string ("") or matches one of your patterns.
DELETE FROM YourTable
WHERE
YourField = ""
OR YourField ALike "511-%"
OR YourField ALike "CARL-%";
With YourField indexed, that pattern matching in the WHERE clause offers a potentially large performance improvement over a query using the Left() function such as your spreadsheet macro used. IOW, the following query would require the db engine to run those Left() expressions on every row of YourTable. But with the query above and YourField indexed, the db engine could simply select the matching rows ... which can easily be an order of magnitude faster.
DELETE FROM YourTable
WHERE
YourField = ""
OR Left(YourField, 4) = "511-"
OR Left(YourField, 5) = "CARL-";
Sub DeleteRows(strVal as string)
strVal = Trim(strVal)
if strVal = "" then exit sub
dim dbs as Database
set dbs = CurrentDB
dbs.execute "Delete * FROM YOURTABLE where YOURFIELD Like '" & strVal & "*'"
set dbs = Nothing
End Sub
then call it for each item
DeleteRows("Carl-")
DeleteRows("511-")
Given that you have 180 possible problem rows, it may make sense to create a problem list table. For example:
ExcelImport
ID ARow
1 Carl-abdre
2 511-ferw2
3 wywr-carl
4 123-456
ProblemList
Problem
511-
Carl-
Query
DELETE
FROM ExcelImport
WHERE ExcelImport.ID In (
SELECT ID
FROM ExcelImport, ProblemList
WHERE ARow Like [Problem] & "*" Or ARow & ""="")
ExcelImport after query
ID ARow
3 wywr-carl
4 123-456
You manage database data using the SQL language. For Access, check:
http://msdn.microsoft.com/en-us/library/bb177896%28v=office.12%29.aspx
Sub DeleteX()
Dim dbs As Database, rst As Recordset
Set dbs = OpenDatabase("Northwind.mdb")
dbs.Execute "DELETE * FROM " _
& "Employees WHERE Title ALike 'FOOBAR-%';"
dbs.Close
End Sub