MS Access
Is it possible to randomize data in one column while keeping the rest of the table intact. I can easily use a query to pull the column and then sort via a random number field, but am having issues putting it back into my table without a relationship.
The database is to keep track of the locks we have placed on lockers in our school. Every semester, I want to randomize the locks in each area so that staff can use a report to move the locks to their new random locations, rather than randomly move the locks on their own and input the new locations into the database. Any help or suggestions would be appreciated.
Thanks,
10 1794
It's a little unclear what you want.
Are you asking for say all the numbers between 1 and 50 in a random order? e.g. 43,20,17, 15,50, 1 .... etc.
Phil
- This can actually be done, though it may not be so simple. One Method would be:
- Create a Recordset based on your Table.
- For a specified number of Iterations, create two Random Record Numbers (Absolute Positions) within the Recordset.
- Move to the first Random Position and retrieve the Value in the [LockNum] Field.
- Move to the second Random Position and retrieve the Value in the [LockNum] Field.
- Swap these two Values and Update the [LockNum] Field in the Recordset.
- The more Iterations that you perform, the more Random the exchange since Random Position #1 could equal Random Position #2.
- All other Field Values are held, only Locker Numbers are swapped.
- There may be an easier approach, but none comes to mind right now.
- Let me know if you are interested and I'll Post the Logic and Code.
Exactly what I came up with.
Phil
That sounds great, but also quite complicated. I would greatly appreciate a post of code and logic if you have the time. Thanks to both of you for your replies.
Initially I set up a table Numbers as below with Num = NumID just to set some initial values.
Numbers
NumID AutoNumber Key
Num Long No Duplicates
[/code]
Here is the code with the comments that I hope explain what is happening -
-
Option Compare Database
-
Option Explicit
-
-
Function Unsort(Counter As Long)
-
-
Dim MyDb As Database
-
Dim NumSet As Recordset
-
Dim SQLStg As String
-
Dim FirstID As Long
-
Dim FirstNo As Integer, LastNo As Integer
-
Dim Max As Integer
-
Dim i As Integer
-
-
SQLStg = "SELECT NumID, Num FROM Numbers;"
-
-
Set MyDb = CurrentDb
-
Set NumSet = MyDb.OpenRecordset(SQLStg)
-
-
With NumSet
-
.MoveLast
-
Max = .RecordCount ' How many numbers
-
For i = 1 To Counter ' How many pairs do we want to interchange
-
-
FirstNo = Int(Rnd * Max) ' To find which 2 numbers to swap
-
If FirstNo <= 1 Then
-
FirstNo = 0
-
End If
-
LastNo = (Rnd * Max)
-
If LastNo >= Max Then
-
LastNo = Max - 1
-
End If
-
-
Debug.Print "First: " & FirstNo & " Last: " & LastNo
-
If FirstNo = LastNo Then ' If numbers are the same, do nothing
-
GoTo NextCounter
-
End If
-
-
.MoveFirst ' First record
-
.Move FirstNo ' Move so many records down
-
FirstID = !Numid
-
FirstNo = !Num ' Save the first number
-
.Edit
-
!Num = -9999 ' Change it to a number that will never be used, otherwise we get a duplicate
-
.Update
-
.MoveFirst ' First record
-
.Move LastNo ' Move so many records down
-
LastNo = !Num ' Save the second number
-
.Edit
-
!Num = FirstNo ' Change secnd number to first number
-
.Update
-
.FindFirst "NumID = " & FirstID ' Find 1st number again
-
.Edit
-
!Num = LastNo ' Change 1st number (-9999) to second number
-
.Update
-
NextCounter: ' Round we go again
-
Next i
-
.Close
-
Set NumSet = Nothing
-
End With
-
-
End Function
-
Phil
This looked like a lot of fun, so here is what I came up with: - Public Sub doRandomize()
-
-
Dim lRecordCount As Long
-
Dim lCount As Long
-
Dim IDs() As Long
-
Dim lSwap As Long
-
Dim lTemp As Long
-
-
Dim sSQL As String
-
Dim oRst As DAO.Recordset
-
-
Randomize
-
lRecordCount = DCount("ID", "Randomize")
-
ReDim IDs(lRecordCount)
-
-
' Get IDs and load them into an Array
-
lCount = 1
-
sSQL = "SELECT ID FROM Randomize ORDER BY ID"
-
Set oRst = CurrentDb.OpenRecordset(sSQL, dbOpenDynaset, dbDenyWrite)
-
Do While Not oRst.EOF
-
IDs(lCount) = oRst!ID
-
lCount = lCount + 1
-
oRst.MoveNext
-
Loop
-
-
' Randomize IDs, iterate through the Array and swap it with some other random Array item
-
For lCount = 1 To lRecordCount
-
lTemp = RoundUp(Rnd * lRecordCount)
-
lSwap = IDs(lCount)
-
IDs(lCount) = IDs(lTemp)
-
IDs(lTemp) = lSwap
-
Next lCount
-
-
' Update Records
-
lCount = 1
-
oRst.MoveFirst
-
Do While Not oRst.EOF
-
oRst.Edit
-
oRst!ID = IDs(lCount)
-
oRst.Update
-
lCount = lCount + 1
-
oRst.MoveNext
-
Loop
-
oRst.Close
-
-
End Sub
-
Public Function RoundUp(ByVal x As Double) As Double
-
RoundUp = IIf(x = Int(x), x, Int(x + 1))
-
End Function
-
Basically, it loads a Column to be randomized into an Array. Then it shuffles the Array. Then writes the shuffled array back into to the Column.
- Here is a solution that I came up with. In hindsight, I do not think that it is the optimal solution, but I'll post it anyway.
- Sample Data with Lock Numbers in sequence:
- Last Name First Name LockNum
-
Cencini Andrew 100
-
Freehafer Nancy 200
-
Giussani Laura 300
-
Hellung-Larsen Anne 400
-
Kotas Jan 600
-
Neipper Michael 700
-
Sergienko Mariya 800
-
Thorpe Steven 900
-
Zare Robert 1000
- Sample Code (well commented):
- Dim db As DAO.Database
-
Dim rst As DAO.Recordset
-
Dim intRecCount As Integer
-
Dim intPos1 As Integer
-
Dim intPos2 As Integer
-
Const conLOOPS As Integer = 10 '10 Iterations of Loop
-
Dim intCtr As Integer
-
Dim intL1 As Integer
-
Dim intL2 As Integer
-
Dim brk1 As Variant
-
-
Randomize
-
-
Set db = CurrentDb
-
-
Set rst = db.OpenRecordset("tblLocks", dbOpenDynaset)
-
-
rst.MoveLast: rst.MoveFirst 'For an accurate Record Count
-
intRecCount = rst.RecordCount 'Record Count contained in intRecCount
-
-
With rst
-
For intCtr = 1 To conLOOPS 'Loop 10 times, mix em up!
-
intPos1 = Int(Rnd * intRecCount) + 1 '1st Random Position
-
.Move intPos1 - 1 'Move to 1st Random Position
-
brk1 = rst.Bookmark 'Set Bookmark to this Position
-
intL1 = rst![LockNum] 'Store Lock# of 1st Position in intL1
-
.MoveFirst 'Move to 1st Record in Recordset
-
intPos2 = Int(Rnd * intRecCount) + 1 '2nd Random Position
-
.Move intPos2 - 1 'Move to 2nd Random Position
-
intL2 = rst![LockNum] 'Store Lock# of 2nd Position in intL2
-
.Edit
-
rst![LockNum] = intL1 'Replace Lock# in 2nd Position with 1st
-
.Update
-
rst.Bookmark = brk1 'Move to the 1st Position via a Bookmark
-
.Edit
-
rst![LockNum] = intL2 'Replace Lock# in 1st Position with 2nd
-
.Update
-
.MoveFirst
-
Next
-
End With
-
-
rst.Close
-
Set rst = Nothing
-
-
DoCmd.OpenTable "tblLocks", acViewNormal, acReadOnly
- tblLocks after Code Execution:
- Last Name First Name LockNum
-
Cencini Andrew 900
-
Freehafer Nancy 200
-
Giussani Laura 700
-
Hellung-Larsen Anne 400
-
Kotas Jan 1000
-
Neipper Michael 300
-
Sergienko Mariya 600
-
Thorpe Steven 800
-
Zare Robert 100
-
- Please forgive the lack of formatting since I simply did not have the time to do so. You can also take a look at the Attachment if you so desire.
Thanks for your help. So far I have had the most success with Phil's solution. One missing factor that I clearly didn't emphasize enough in my original post is that I want the locker numbers to only be swapped within their current area. I tried adding a WHERE clause in Phil's code, but it seems to be ignored in my testing. Below I am going to provide my table layout for tblLocks.
ID (Autonumber)
Lock (String engraved on back of lock)
Combo (combination to open the lock)
Area (1 to 5 signifying different wings in the building)
Location (locker number that the lock is on or needs to be moved to, this is the column that needs to be shuffled)
OLocation (I copy the Location column to this column prior to doing any switching so that I can create a report on where locks need to be moved for the staff that do that work)
Again, any help is greatly appreciated. I am learning from the code provided and have tried hard to make it work on my own. Thanks in advance for any additional help.
Cheers,
Ultimately, I would love to be able to provide a solution where the users click a button on the form and the locks are shuffled within their current areas. Then I will have a report generate showing the lock swaps they need to make, which they can cross off as they make the physical changes in location.
The very simple way (Not the best) is to add an initial single digit in front of the Lock Number to represent each of your 5 Locations.
The code remains the same, but your reports need the Left$(LockNo,1) for the Location, and the Mid$(LockNo,2) for the lock no.
The better way, and probably easier to set up, is to create a Location Table with LocationID & Location and add a LocationID column to Locks Table.
The code would be similar, but you would in addition, need to save and swap the LocationIDs.
Thinking about it, the second option is much better as you can process one location at a time.
Phil
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Albretch |
last post by:
I am trying to insert some textual data belonging to an HTML page into
a table column with 'TEXT' as data type
mysql's maual _/manual.html#String_types tell you, you may insert up
to (2^16 - 1),...
|
by: Kevin Myers |
last post by:
Hello,
I'm an experienced application developer in some languages (including
various SQL dialects), but have very little experience with MS Access or
VBA, and am having trouble figuring out how...
|
by: Bob |
last post by:
Background
1. I create a data table that has one primary key and one unique column with other columns as well
2. I then Bind it to my list countrol setting the DataSource to my table name and...
|
by: Woody Splawn |
last post by:
Lets say I have a winform that is populated with a dataset. The dataset and
data table may have several rows in it. Lets say I am looking at the
winform and I want to assign a value to a certain...
|
by: Ron L |
last post by:
I have a data table that lists a series of items in my database. In my user
form, I want the user to be able to filter by a number of criteria (e.g.
location, contract, date modified, etc). Other...
|
by: Vasilis X |
last post by:
Here is the question :
I have a data table, UnShorted, which has a data column EventTime (type :
date time) and a data column Values (type : single).
I want to create a table, Shorted, that...
|
by: rodchar |
last post by:
hey all,
Dim _dt As New DataTable("Controls")
_dt.Columns.AddRange(New DataColumn() _
{New DataColumn("Name"), New DataColumn("Type")})
I saw this excerpt in an article on creating a stand...
|
by: Scot L. Harris |
last post by:
Currently using Postgresql 7.2.4-5.80 with php 4.2.2.-8.0.8 on a redhat
8.0 system.
I am writing some php scripts where I want to generate a list of the
column names in a particular table that...
|
by: blitzenn |
last post by:
I am attempting to use triggers to add some simple auditing to my database structure (SQL Server 2005). I am running an ASP with this so I have many databases (dozens) with identical structure. My...
|
by: gs |
last post by:
How do I quickly make a c# windows project adapt to sql table columns change
such as length quickly?
I am using datagridview and detailview. I am not dealing with asp.net
I have to manually...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |