I have two tables that I wish to compare records - based on a field values. Here is what I tried :
Dim RCount As Long
Dim Rst As Recordset
Dim Rst1 As Recordset
Dim f As Field
'Current Record set
Set Rst = CurrentDb.OpenRecordset("Table1")
Set Rst1 = CurrentDb.OpenRecordset("Table2")
With Rst
For Each f In Rst1.Fields
RCount = DCount("FieldFromTable1", "Table1", "[FieldFromTable1]='" & Me.[FieldFromTable2].Value & "'")
If RCount > 0 Then
Me.Checkbox1.Value = True
End If
Next f
End With
Rst.Close
Rst1.Close
Here is my updated question, something like that I'm trying to accomplish. But still this code cycles only through currently selected record in my Table2 form.
Following on from my comment. You can use recordcounts to see if there is a record that exists and matches. You could use the following query to see if a record exists:
dim rst as recordset
dim varSQL as string
varSQL = "SELECT [fieldfromtable1] FROM Table1 WHERE [fieldfromtable1] ='" & [fieldfromtable2].value & "'"
Set Rst = CurrentDb.OpenRecordset(varSQL)
If rst.recordcount = 1 then
MsgBox "Fields have matching values !"
End If
rst.close
You could replace the =1 with >0.
Alternatively, I think you can use dcount() function which would be something like:
dim RCount as long
Rcount = dcount("fieldFromTable1","table1", "[fieldFromTable1]='" & me.[FieldFromTable2].value & "'")
if Rcount > 0 then
MsgBox "Fields have matching values !"
end if
again, you can use >0 or =1 im not sure which is most appropriate for your situation.
Edit
the following query can be performed to update the checkbox, but this isn't at form level
UPDATE table1 INNER JOIN table2 ON table1.[fieldfromtable1] = table2.[fieldfromtable2] SET table1.[checkboxField] = True
WHERE table2.[fieldfromtable2]= table1.[fieldFromtable1]
I haven't really consider an option to just UPDATE records in tables. Thsi is what It worked for me. I was just trying to set Checkbox to TRUE when record from Table1 meets criteria in Table2. A simple UPDATE solved the problem:
Dim SQL As String
niz = " UPDATE Table2" & _
" INNER JOIN Table1" & _
" ON Table1.FieldFromTable1=Table2.FieldFromTable2" & _
" SET Table2.Checkbox1=True"
DoCmd.SetWarnings False
DoCmd.RunSQL niz
DoCmd.Requery
DoCmd.SetWarnings True
Related
VBA/Macro newbie needing help with the above mentioned.
Table: Inventory
Product Value a Value b
1. Product 1 0 0
2. Product 2 0 0
3. Product 3 0 0
Query: Qry
Product Value VAL
1. Product 1 100 a
2. Product 2 200 a
3. Product 3 300 b
Result of Marco
Table: Inventory
Product Value a Value b
1. Product 1 100 0
2. Product 2 200 0
3. Product 3 0 300
Without changing the schema or thinking of alternative methods: I specifically need a macro (not an update query) to update corresponding products in table.field "Inventory.Value" with a value from query "qry" depending on whether it is in column a or column b as stated in the table.
I know that there will be an iif statement involved and a insert into but for the life of me I just cannot make it work.
EDIT: I am open to alternative ideas with the same result.
This is a watered down version of the database.
Thank you for the skeleton guys, it helped tremendously
This is the Macro (the fields and table names are different to my original post)
Option Compare Database
Option Explicit
Sub Opdateer()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim sql As String
Set dbs = CurrentDb
sql = "SELECT Orders.Warehouse, OrderDetail.Product, OrderDetail.OrderDetailStatus, Sum(OrderDetail.Qty_mt) AS SumOfQty_mt FROM Orders INNER JOIN OrderDetail ON Orders.ID = OrderDetail.OrderNumber GROUP BY Orders.Warehouse, OrderDetail.Product, OrderDetail.OrderDetailStatus;"
Set rst = dbs.OpenRecordset(sql, dbOpenDynaset)
With rst
Do Until rst.EOF
If !OrderDetailStatus = "Allokeer" Then
sql = "UPDATE [InventoryCT] SET [StockAllocated] = " & !SumOfQty_mt & " WHERE [ProductCT] = " & !Product & " ;"
dbs.Execute (sql)
Else
sql = "UPDATE [InventoryCT] SET [StockOpgelaai] = " & !SumOfQty_mt & " WHERE [ProductCT] = " & !Product & " ;"
dbs.Execute (sql)
End If
.MoveNext
Loop
End With
rst.Close
dbs.Close
End Sub
You could try something like this;
Dim rst As DAO.Recordset
Dim sql As String
sql = <The sql string for your query>
Set rst = CurrentDb.OpenRecordset(sql, dbOpenDynaset)
With rst
Do Until .EOF
If !VAL = "b" Then
sql = "UPDATE Inventory SET [Value b] = " & !Value & " WHERE Product = '" & !Product "' ;"
CurrentDB.Exectute sql
End If
.MoveNext
Loop
End With
I am trying to count number of fields in a table in Access 2010. Do I need a vb script?
You can retrieve the number of fields in a table from the .Count property of the TableDef Fields collection. Here is an Immediate window example (Ctrl+g will take you there) ...
? CurrentDb.TableDefs("tblFoo").Fields.Count
13
If you actually meant the number of rows instead of fields, you can use the TableDef RecordCount property or DCount.
? CurrentDb.TableDefs("tblFoo").RecordCount
11
? DCount("*", "tblFoo")
11
Using a query:
'To get the record count
SELECT Count(*) FROM MyTable
In DAO it would look like:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT * FROM MyTable")
rst.MoveLast
'To get the record count
MsgBox ("You have " & rst.RecordCount & " records in this table")
'To get the field count
MsgBox ("You have " & rst.Fields.Count & " fields in this table")
Note, it is important to perform the MoveLast before getting the RecordCount.
In ADO it would look like:
Set conn = Server.CreateObject("ADODB.Connection")
conn.Provider = "Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("MyDatabaseName.mdb"))
Set rst = Server.CreateObject("ADODB.recordset")
rst.Open "SELECT * FROM MyTable", conn
'To get the record count
If rst.Supports(adApproxPosition) = True Then _
MsgBox ("You have " & rst.RecordCount & " records in this table")
'To get the field count
MsgBox ("You have " & rst.Fields.Count & " fields in this table")
Quick and easy method: Export the table to Excel and highlight row 1 to get number of columns.
I have two tables and I have a form linking to one of them. I want to check a value and if it is true, add the record the other table by using VBA.
Can anyone help me, please?
This is my code, but it does not work:
Dim rec1 As DAO.Recordset
Dim rec2 As DAO.Recordset
Set rec1 = CurrentDb.OpenRecordset("TotalTPAq")
Set rec2 = CurrentDb.OpenRecordset("Visi")
rec1.MoveFirst
Do Until rec1.EOF
If rec1!Date = PlanDate.Value Then ' planDate is a text box
rec2.AddNew
rec2![Planing Date History] = PlanDate.Value
rec2.Update
rec2.Close
End If
rec1.MoveNext
Loop
rec1.Close
Set rec2 = Nothing
Set rec1 = Nothing
DoCmd.Close
This should provide a start for you:
'Run query to fill table
Private Sub btnRnQry_Click()
'No value entered
If IsNull(Me.txtEntry) Or Me.txtEntry = "" Then
MsgBox ("Is null or empty")
Else
'Assign value to variable
Dim entry As String
entry = Me.txtEntry
Dim sql As String
sql = "INSERT INTO tableTwo ([First Name],Surname,[Phone Number] )" & _
"SELECT * " & _
"FROM tableOne " & _
"WHERE [First Name] = '" & entry & "';"
'Run the SQL
DoCmd.RunSQL sql
End If
End Sub
How can i compare two MS ACCESS 2007 databases.Both databases contain same tables with same feilds ad structure.i need to compare the record values between two databases to detect any difference in record values.
ACCESS 2007 Database1
serial no. | NAME | ADDRESS
1 smith street 1
2 john street 4
3 alix street 8
ACCESS 2007 Database2
serial no.| NAME | ADDRESS
1 smith street 1
2 jhn stret 4
3 alix street 8
I need a VBA code for ms access that can detect the differece of records,just as the records at serial number two.
First thing you should do is link in one of the tables to the other database, e.g link the Database 2 table into database one (this allows both to be queried together) then you could use this simple example with concatenation to determine if all the fields strung together match based on the serial number:
SELECT T1.*, T2.*
FROM Table1 As T1, Table2 As T2
WHERE T2.[serial no.] = T1.[serial no.]
AND T2.[NAME] & T2.[ADDRESS] <> T1.[NAME] & T1.[ADDRESS]
You could also specify the columns with each of their own condition if you prefer.
NOTE: This is assuming you are only looking for differences where the serial no matches, if you also need to identify records that may appear in one table but not the other then you will need to use an "Un-matched" query, the query designer can help you with this or post back and I can update my answer.
Option Compare Database
Private Sub Command4_Click()
Dim tablename1, tablename2 As String
tablename1 = Text0.Value
tablename2 = Text2.Value
'On Error GoTo Err_cmdValidateGeneralInfo_Click
Dim F As DAO.Field
Dim rs As DAO.Recordset
Dim rs1 As DAO.Recordset
Set curDB = CurrentDb()
'If Me.DateModified = Date Then
'Adds new employees to the TT_GeneralInfo table in the FTEI_PhoneBook.mdb - which is used thru out the AP databases.
' DoCmd.OpenQuery "qryEmpData_TT_General"
strsql = "Select * from " & tablename1
Set rs = curDB.OpenRecordset(strsql)
strsql1 = "Select * from " & tablename2
DoCmd.CopyObject , "Unmatched_records", acTable, tablename1
curDB.Execute "DELETE FROM Unmatched_records"
Set rs1 = curDB.OpenRecordset(strsql1)
Do Until rs.EOF
For Each F In rs.Fields
If rs.Fields(F.Name) <> rs1.Fields(F.Name) Then
'rs.Edit
strsql = "Select * into test from " & tablename1 & " where " & F.Name & " = """ & rs.Fields(F.Name) & """"
DoCmd.RunSQL strsql
If DCount(F.Name, "test") <> 0 Then
GoTo append_unmatch
'appending unmacthed records
append_unmatch:
strsql2 = "insert into Unmatched_records Select * from test"
DoCmd.RunSQL strsql2
'if record doesnt match move to next one
GoTo Nextrecord
End If
' rs.Fields(F.Name) = rs1.Fields(F.Name)
' rs.Update
End If
Next F
Nextrecord:
rs.MoveNext
rs1.MoveNext
Loop
'To check whether tables matched or not
Dim rs2 As DAO.Recordset
strsql3 = "select * from Unmatched_records"
Set rs2 = curDB.OpenRecordset(strsql3)
For Each F In rs2.Fields
If DCount(F.Name, "Unmatched_records") <> 0 Then
MsgBox ("The two tables didnt match. Check table test for unmatching reocrds.")
Else
MsgBox ("Tables match!")
End If
Exit Sub
Next F
rs2.Close
End Sub
I have two fields, one is just the number of the other one, e.g. Field 1 = "12AB" and Field 2 is "12". I'm trying to make Field 2 auto-update but I'm not sure how.
I'm trying to get:
ClassName ClassYear
12AB 12
13BU 13
15BE 15
But instead the whole fields update to the number in the last one:
ClassName ClassYear
12AB 15
13BU 15
15BE 15
The code I currently have is
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordset("MasterTable")
With rst
Do Until .EOF
.Edit
If (Left(ClassName.Text, 1) = "1") Then
!ClassYear = Left(ClassName.Text, 2)
Else
!ClassYear = Left(ClassName.Text, 1)
End If
.Update
.MoveNext
Loop
.Close
End With
Help is much appreciated! Thank you :)
How about something on the lines of:
sSQL = "UPDATE MasterTable SET ClassYear=Left(ClassName,2) " _
& "WHERE Left(ClassName,1)='1'"
CurrentDB.Execute sSQL, dbFailOnError
sSQL = "UPDATE MasterTable SET ClassYear=Left(ClassName,1) " _
& "WHERE Left(ClassName,1)<>'1'"
CurrentDB.Execute sSQL, dbFailOnError