Filtering Data from a specific column - ms-access

Hello Everyone I am at a dilemma I am trying to find out a way to filter out certain data in a column field I have an idea on how to do this but I do not know the correct syntax to use. First here is the table and here is the code structure I would like to write.
for i=1 to length of column First Match
for j=1 to length of column Second Match
If ((value of the data in column First Match = 15) OR (value of the data in column FirstMatch = 1)) AND
((value of the data in column Second Match = 15) OR (value of the data in column Second Match = 1))
Then
Filter the data and append so the filtered datas are saved for both First Match and Second Match
end if
next
next
I am trying to filter out the data that is a 15 and 1 so that only data that have the values 0,2,3,4,5,6...14 will be shown for instance the information of john and steve will not be shown because both the first and second match fields have a 1 or 15 but the rest of data will be shown my form is a split form setup.
Is my method correct?
First Name Last Name First Match Second Match
James Matheson 0 2
Monroe Labonson 4 3
Barack Obama 2 5
Frederick Douglas 3 4
Steve MCGowan 1 1
John Seals 15 15
Mike Omalley 14 15
Set rs = CurrentDb.OpenRecordset("Table1")
Do While Not rs.EOF
If rs!Fields("First Match") > 1 And rs!Fields("First Match") < 15 And rs!Fields("Second Match") > 1 And rs!Fields("Second Match") < 15 Then
End If
Loop

With a better understanding (I hope) I've reproduced your data in Access and built a query that does what you seem to ask. The best way to see this is to create a new query, not add a table, and go directly to SQL view. Paste the following SQL statement (the one in quotes) in and replace matchFilter with your table name.
In your event code you can create a recordset based on the SQL:
Dim sSQL as string, rs as Recordset
sSQL = "SELECT matchFilter.[First Name], matchFilter.[Last Name], matchFilter.[First Match], matchFilter.[Second Match] " & _
"FROM matchFilter " & _
"WHERE ((([First Match]<>1 And [First Match]<>15 And [Second Match]<>1 And [Second Match]<>15)=True))"
Set rs = CurrentDB.OpenRecordset(sSQL)
' now do what you want
Wrong answer below!
Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset("yourTableName")
Do While Not rs.EOF
If rs!Fields("col1") > 1 AND rs!Fields("col1") < 15 AND rs!Fields("col2") > 1 AND rs!Fields("col2") Then
'do what you have to do with filtered out records
End If
Loop

I have found the solution apparently it was just a misunderstanding because the first time I tried this code I thought it was wrong but it was because my field names did not have spaces in between the first time I wrote them.
Me.Filter = ""
Me.Filter = "[First Nam]<>'Jamie' AND [Last Nam]<>'Cartman'"
Me.FilterOn = True

Related

ACCESS sql code to multiply record with calculated value from previous cell

I am using Access Database to get a value. I am fairly new to access as I usually use SQLServer and I am having trouble in getting what I want.
I have the following table, with column TARGET and incremental Target as the target column that I need to get:
Category|Period|Value| TARGET |
A | 4 | 1 | 1/1 =1 |
A | 3 | 3 | 1/(3*1)=0.33 | (1/value at period 3 * previous target)
A | 2 | 6 |1/(0.33*6)=0.505|
A | 1 | 9 |1/(0.505*9)=0.22|
The data is partitioned by Category and ordered in descending order by Period.
For the first row the Target should be: (1/value at current period)
For the next rows the Target should be: (1/value at current period * value of previous target)
As you can see this is somehow complex as I need to evaluate a cell value and then for the next row I need to use the value in the cell above.
Plus I need to get the incremental value for this column as well.
Any help will be very much appreciated as I am new to Access and need to get this done soon!
Here is a function placed in general module that can be called from query. Value is a reserved word so I used Data for that field name.
Option Compare Database
Option Explicit
Global dblTar As Double
Global strCat As String
____________
Function CalcTarget(strC As String, dblT As Double) As Double
If strCat <> strC Then
strCat = strC
dblTar = dblT
End If
dblTar = 1 / (dblT * dblTar)
CalcTarget = dblTar
End Function
Calling function in query:
SELECT Category, Period, Data, CalcTarget([Category],[Data]) AS Target FROM Table1;
Normally I advise not to save calculated data to table when a query can work, but if you prefer to save, then options are:
An UPDATE action: UPDATE Table1 SET Target = CalcTarget([Category],[Data]);
Or VBA:
Sub CalcTarget()
Dim rs As DAO.Recordset
Dim strCat As String
Dim dblTar As Double
Set rs = CurrentDb.OpenRecordset("SELECT * FROM table1 ORDER BY Category, Period DESC")
strCat = rs!Category
dblTar = rs!Data
Do While Not rs.EOF
If rs!Category = strCat Then
dblTar = 1 / (rs!Data * dblTar)
rs.Edit
rs!Target = dblTar
rs.Update
rs.MoveNext
Else
strCat = rs!Category
dblTar = rs!Data
End If
Loop
End Sub

Microsoft Access: Remove duplicate from Table and replace with Random list from table

I have a table in access with two fields: state and city. The state is unique and the city should be the same.
I have a table that shows duplicate states with the same city. I want to make the city that is duplicate to be random within the state. I have another table that calls out the cities in the states.
I currently have:
State
Washington Seattle
Washington Seattle
I want it to be:
Washington Seattle
Washington Bellevue
How do i remove the duplicate city and replace one of it with a random city in the state like the example above?
Assuming that i have a separate table that I can create to call out all the cities in a state.
I have no idea how to tackle this issue. Thanks for the help.
One possible way to do this (based on your comment) is to add two fields to your city table. Call it something like [Used] and [DateUsed]. use some type of random function to pick your cities. As you use the city, change the [used] field to true and put today's date in the [Dateused] field. Use a query to pull only the cities that are marked False. You can run a daily query, any [Dateused] that is older than 2 days you can clear the true flag from the [used] field and clear the [DateUsed] field.
dim db as dao.databse
dim rs as dao.recordset
dim sql as string
dim x as integer
x = 0
set db = currentdb
Do While X < 20
sql = "SELECT * FROM [tblcities] WHERE [Used] = false AND stateID = " & some value for stateID
set rs = db.openrecordset(SQL,dbopenDynaset)
if rs.recordcount > 0
rs.movefirst
do while not rs.eof
if randomfunction() = true //just an example, you'll have to come up with the random function on your own.
SQL = "UPDATE [tblCities] SET [Used] = True, [DateUsed] = DATE() WHERE StateID = " & Some Value for StateID & " AND CityName = '" & rs!cityName & "'"
docmd.RunQuery SQL
break do
end if
rs.movenext
loop
end if
set rs = nothing
x = x + 1
loop
set rs = nothing
set db = nothing
(rough code, I'm sure there are lost of little typo or syntax error, but this not meant to be a complete example, only to point you in a direction.)

Filtering Data using record sets

Hello everyone I am at a dilemma I am trying to find possible multiple accounts made by the same person by comparing the records, my main problem is how do you compare the current row value to the next value? By this I mean like this MI(i)=MI(i+1) "MI" is the field that I am targeting and i represents the current row, so what this is suppose to do is compare the current value to the next value. But it does not seem to work in vba is it done a diffferent way? To filter should I use rs.Filter or should I use Me.Filter because I want the filtered table to show up in my splitform.
Current Example Table that I am working with:
Number MI First Name Last Name DOB
15241543 123456789 James Matheson 2/25/1980
15241543 123456789 Jams Matheson 2/25/1980
12345679 124512451 Monroe Matheson 3/25/1980
12345679 124512451 Monro Matheson 3/25/1980
54789654 152415241 Dilan Pumley 4/23/1970
54789658 154215246 Michael Lan 1/30/1989
Final table that should appear is this:
Number MI First Name Last Name DOB
15241543 123456789 James Matheson 2/25/1980
15241543 123456789 Jams Matheson 2/25/1980
12345679 124512451 Monroe Matheson 3/25/1980
12345679 124512451 Monro Matheson 3/25/1980
Private Sub buttonSort_Click()
Dim i As Integer
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("deleteYo")
For i = 0 To rs.RecordCount - 1
'Comapred the current DOB cell value to the next DOB cell value and some other conditions are set such as Current First Name does not equal the next First Name value
If DOB(i) = DOB(i + 1) And [First Name](i) <> [First Name](i + 1) Or [Last Name](i) <> [Last Name](i + 1) And Number(i) = Number(i + 1) Or MI(i) = MI(i + 1) Then
'Filters the current value if the conditon is passed
Me.Filter = "[First Name]" & [First Name](i).Value & "'"
'Filter the next value also to append the filtered values so that they will not be overwritten.
Me.Filter = Me.Filter & "[First Name]" & [First Name](i + 1).Value & "'"
Else
End If
rs.MoveNext
Next i
Me.FilterOn = True
rs.Close
Set rs = Nothing
db.Close
End Sub
Please Note I have tried using a query with SQl statement for this which does not work properly perhaps because this data is practically millions of records and also because the UI is in the form and when the filtered values are applied I would like them to show up at the table at the bottom of the split form.
You can try using a corelated subquery.
SELECT t.ID, t.[First Name], t.[LastName], t.MI
FROM YourTable AS t
LEFT JOIN
(SELECT t2.id, t2.[First Name], t2.[Last Name], t2.MI
FROM YourTable AS t2) AS temp
ON t.MI = temp.MI
WHERE t.[First Name] != t2.[First Name]
OR
t.[Last Name] != t2.[Last Name];
This is going to compare each field with the same MI value and retrieve records where the first and last names are not similar.
You can adjust the fields to better fit your table schema.

Excel Macro to concatenate multiple rows from Column B per ID rows in Column A with newlines

This problem is in an Excel .xls file.
Simplest Use Case:
Column A has one row.
Column B has 5 rows.
The 5 rows in Column B need to be merged into one row, delimited by newlines.
I have a huge .xls document where there are a ton of IDs in column A.
There are on average anywhere from 3 to 10 rows that belong to each column A row.
How to know which Column B rows belong to which Column A?
By the positioning of the cells.
One Column A row may have 5 Column B rows to the right of it.
I don't have any VBA experience.
I have looked around for macros and functions but haven't had any luck finding anything that matches this problem.
Edit:
I am now trying to figure out how to get the script to ignore rows that have a one-to-one mapping between column A and column B.
Edit again - 06-20-2012:
Now that I can attach images, here is a screenshot of an image for what I'm trying to get.
The rows for Brian and Mark should be ignored, while Scott and Tim get their values copied over.
Edit:
Unmerging column A, using the code that Andy supplied, and then using this VB script afterwards does the trick:
Sub mergeA()
For i = 2 To Cells(65535, 1).End(xlUp).Row
If IsEmpty(Cells(i, 1)) Then Range(Cells(i - 1, 1), Cells(i, 1)).Merge
Next
End Sub
That VB script puts the cells in column A back together
I didn't make the script, it came from this web page:
http://www.vbforums.com/showthread.php?t=601304
This will transform the data shown on the left to the output on the right:
Option Explicit
Sub Make_Severely_Denormalized()
Const HEADER_ROWS As Long = 1
Const OUTPUT_TO_COLUMN As Long = 3
Const DELIMITER As String = vbNewLine
Dim A_Range As Range
Dim B_Range As Range
Dim A_temp As Range
Dim B_temp As Range
Dim B_Cell As Range
Dim Concat As String
On Error GoTo Whoops
Set A_Range = Range("A1").Offset(HEADER_ROWS)
Do While Not A_Range Is Nothing
Set B_Range = A_Range.Offset(0, 1)
' some helper ranges
If A_Range.Offset(1, 0).Value = "" Then
Set A_temp = Range(A_Range, A_Range.End(xlDown).Offset(-1, 0))
Else
Set A_temp = A_Range.Offset(1, 0)
End If
Set B_temp = Range(B_Range, B_Range.End(xlDown)).Offset(0, -1)
' determine how high "B" is WRT no change in "A"
Set B_Range = Range(B_Range, B_Range.Resize( _
Application.Intersect(A_temp, B_temp, ActiveSheet.UsedRange).Count))
' loop through "B" and build up the string
Concat = ""
For Each B_Cell In B_Range
Concat = Concat & B_Cell.Value & DELIMITER
Next
Concat = Left(Concat, Len(Concat) - Len(DELIMITER))
' do the needful
A_Range.Offset(0, OUTPUT_TO_COLUMN - 1).Value = Concat
' find the next change in "A"
If A_Range.Offset(1, 0).Value = "" Then
Set A_Range = Application.Intersect(A_Range.End(xlDown), ActiveSheet.UsedRange)
Else
Set A_Range = A_Range.Offset(1, 0)
End If
Loop
Exit Sub
Whoops:
MsgBox (Err & " " & Error)
Stop
Resume Next
End Sub

Create a field name from a recordset

I have a form that displays information on a project that has 10 check boxes. The check boxes are named "chkAudience1", "chkAudience2", etc through "chkAudience10". Any combination of boxes can be checked from none to all and anything in between.
Then I have a table that links the check boxes to the project. This table contains a field called ProjectID and a field called AudienceID (both fields are defined as number). This allows me to select all audience records for a project.
The problem is that I want to loop through the records for a project and check the boxes that match a record in the table. My current code looks like:
sqlStmt = "SELECT * FROM ProjectAudience WHERE ProjectID = " & Me.ProjectID.Value
Set rs = cn.Execute(sqlStmt)
While Not rs.EOF
'Me.chkAudience1.Value = -1
x = "Me.chkAudience" & rs(1).Value
x.Value = -1
rs.MoveNext
Wend
x will be set to "Me.checkAudience1", but the next line produces an "object required" error. How do I create a field name based on recordset data and then use that field name to set a value. (This is being done is Microsoft Access 2003)
The correct while loop is:
While Not rs.EOF
'Me.chkAudience1.Value = -1
Me.Controls("chkAudience" & (rs(1).Value)).Value = -1
rs.MoveNext
Wend
The key is the Me.Controls().