473,394 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How do I use VBA to Swap Data Between a Field in Two Different Records - Access 2003

4
How do I create code to swap data in a field for two different records in Access 2003? I want to create a button on a form that will allow me to swap data for a field. For example, if I have a field named asset, I want to swap the asset field information for one record with the asset field information from another record at the same time. record1 asset field information goes to record2 asset field information and record2 asset field information goes to record1. Is this possible?
Sep 12 '11 #1
19 4721
nico5038
3,080 Expert 2GB
For a swap you'll always need a temp storage of the field(s) to be swapped.
You can do this by creating a temp table, or by using VBA and store the temp field in a variable.

Temp table approach is to insert the source table record in the emptied temptable, next "move" the target table to the source and finally move the temp table record to the target table.

Getting the idea?

Nic;o)
Sep 12 '11 #2
NeoPa
32,556 Expert Mod 16PB
Yes it's possible.

Without more information in the question though it's hard to offer any meaningful advice. It makes more sense to determine a proper question before posting it.
Sep 12 '11 #3
cw11
4
let me see if I can do a better job. I have a database of computers. On occasion, we will assign a pc to another person from our inventory. I want to take a pc that is assigned to user John and assign it to Frank. At the same time, I want to assign Frank's pc to John. That is what I mean by swap. Thanks in advance
Sep 12 '11 #4
nico5038
3,080 Expert 2GB
The "Normalized way to do this is to create a relation table connecting a PC to a user.
A swap than implies inserting two records with the new situation.

I would use a relation table with the fields:
User_ID, PC_ID, DateStartUse

Thus you have a historical view when a PC was used by which user...

Nic;o)
Sep 12 '11 #5
NeoPa
32,556 Expert Mod 16PB
It seems I need to make myself clearer. Apologies for the confusion.

I'm not confused about what 'swap' means. I'm short of information that describes the circumstances you envision where you are choosing to swap information between records.

Are you, for instance, displaying both records on a form (not too straightforward in itself) and intending to click a Command Button to swap them? Maybe you have some other method for determining which records are to have their data swapped. Without knowing such important information as this we don't really have much of a question to work on or with.

@Nico
The Normalisation point is always worth making, but must it necessarily require such a separate table if the individual user is considered to have the capacity for only one PC? I would imagine an FK value in the [Person] (My guess at the name of the table referred to in the question) record (in the field named [Asset]) would make normalised sense.

@CW11
If the concept of Normalisation is a new one for you then check out Database Normalisation and Table structures.

As I mentioned earlier, it's certainly possible to do. I would suggest a fuller explanation of exactly what you're dealing with would make it possible to provide more helpful advice on the subject.
Sep 12 '11 #6
nico5038
3,080 Expert 2GB
@NeoPa,

I like "general" and "foolproof" solutions. Having a relation table will allow the restraint of one PC per user by adding a "Unique" constraint on the user key, but by removing that restraint you can allow multiple.
More over, you get also the possibility of looking into the history of the PC's and users and e.g. counting the number of swap's per department, etc.

Regards,

Nic;o)
Sep 13 '11 #7
NeoPa
32,556 Expert Mod 16PB
I understand, and I don't argue with any of your points :-)
Sep 13 '11 #8
cw11
4
Here is the way the database looks. I have a field username. I have another field PC. I have created a form. In the form I have a field username1 and username2. I have a field Serial1 and Serial2. I will fill in the four fields with the usernames and Serial numbers from combo boxes for those fields. I will choose manually the names and PC that I want to swap based on when I physically move a pc from one office to another. I then will come back to my office and pull up the two user names and PC's and swap only the user names for the two records in question. The combination of Serial number and username makes my argument unique. I then want to create and update query that sap the usernames based on four variables for the swap button. Again the variables created will be for username1, username2, Serial1 and Serial2. This is how I will trap the records that I want to swap.
Sep 13 '11 #9
NeoPa
32,556 Expert Mod 16PB
I think I'm getting you now. The terminology of fields for a form is not accurate, but nevertheless unfortunately common, so is not too obscure (Forms have controls that, when bound, reflect the values of fields). I would assume from what you say that you have four unbound ComboBox controls. If they do not already filter depending on selection that would be a good idea to implement anyway (See Example Filtering on a Form).

Supper coming so I hope to come back later and finish off with some suggestions that are actually helpful.
Sep 13 '11 #10
NeoPa
32,556 Expert Mod 16PB
For this sort of logic I would actually recommend Recordset processing rather than SQL commands and use a defined transaction to ensure the swap is either done completely or not at all.

The basic logic would be :
  1. Open the recordset.
  2. Navigate to the first record.
  3. Save the value to be swapped in a variable in your code.
  4. Navigate to the second record.
  5. Save the value to be swapped from this record in a separate variable
  6. Begin a transaction.
  7. Edit the current record (The second) to contain the first saved value.
  8. Save this record.
  9. Navigate again to the first record.
  10. Edit this record to contain the saved value taken from the second record originally.
  11. Save this record.
  12. Commit the transaction.
  13. Close the recordset.

I'm off now for a week so I hope this is enough for you. If it's not, and no-one else can pad it out in the meantime, I'll see what I can do for you when I get back (but I doubt that will be required).
Sep 14 '11 #11
cw11
4
This looks great. Thanks so much for your help.
Sep 14 '11 #12
NeoPa
32,556 Expert Mod 16PB
My pleasure.

Let us know how you get on with this. I'm sure to catch up when I return.
Sep 14 '11 #13
ADezii
8,834 Expert 8TB
@cw11: Based on your specifications, the following approach has been tested and will work (Swap User Names only, based on the pairings of 2 Unique Combinations of User and Serial Number):
Expand|Select|Wrap|Line Numbers
  1. Dim strUser1 As String
  2. Dim strUser2 As String
  3. Dim strSerialNum1 As String
  4. Dim strSerialNum2 As String
  5. Dim strCriteria1 As String
  6. Dim strCriteria2 As String
  7.  
  8. strUser1 = "ADezii"
  9. strSerialNum1 = "555B7"
  10. strUser2 = "NeoPa"
  11. strSerialNum2 = "KLY76"
  12.  
  13. strCriteria1 = "[User] = '" & strUser1 & "' And [SerialNum] = '" & strSerialNum1 & "'"
  14. strCriteria2 = "[User] = '" & strUser2 & "' And [SerialNum] = '" & strSerialNum2 & "'"
  15.  
  16. 'Do PCs even exist for the Unique Combination of User/Serial Number?
  17. If DCount("*", "tblPCs", strCriteria1) > 0 And _
  18.    DCount("*", "tblPCs", strCriteria2) Then
  19.      'Perform the Swapamundo
  20.      CurrentDb.Execute "UPDATE tblPCs SET [User] = '" & strUser2 & "' WHERE " & _
  21.                         strCriteria1, dbFailOnError
  22.      CurrentDb.Execute "UPDATE tblPCs SET [User] = '" & strUser1 & "' WHERE " & _
  23.                         strCriteria2, dbFailOnError
  24. Else
  25.     MsgBox "One or both PCs do not exist for the specified combination of User and " & _
  26.            "Serial Number", vbExclamation, "Swap Aborted"
  27. End If
Sep 14 '11 #14
NeoPa
32,556 Expert Mod 16PB
Interesting suggestion ADezii, but doesn't treat the swap as a single transaction. Almost certainly thoroughly adequate of course, but I think you'd find it interesting to pad out my pseudo-code from post #11 into VBA proper using the names of the objects provided by the OP in post #9. If you haven't played with transactions before it's well worth getting into. Just a suggestion of course, and only if it interests you. I'll do it myself when I get back if I find the OP still needs it.

As a side-note - what is going on with you providing a SQL solution instead of a VBA one (:-D)? That's not what I expect from you, but it's good to see nevertheless. It doesn't hurt to see that both approaches can be made to work. See you at the end of next week.
Sep 14 '11 #15
ADezii
8,834 Expert 8TB
As a side-note - what is going on with you providing a SQL solution instead of a VBA one (:-D)?
@NeoPa: Don't know what is going on with me - SQL instead of VBA? (LOL).
  1. Is encapsulating the Swap in a Transaction really necessary once the following evaluates to True?
    Expand|Select|Wrap|Line Numbers
    1. 'Do PCs even exist for the Unique Combination of User/Serial Number? 
    2. If DCount("*", "tblPCs", strCriteria1) > 0 And _ 
    3.    DCount("*", "tblPCs", strCriteria2) > 0 Then 
  2. Transactions do imply additional overhead, don't they?
Sep 15 '11 #16
NeoPa
32,556 Expert Mod 16PB
  1. I think so. Yes.

    Consider the situation where the power fails after the first record is changed and before the second one is.

  2. Yes. Negligible in this case I would expect, but certainly there.

    Actually, probably less of an overhead than using two separate SQL strings instead of a single opening of the table within a VBA recordset (logically - I have no experimental timings to support that but as opening a table is where most of the overhead comes in when accessing it I would expect two of them to take longer than a single one).
Sep 24 '11 #17
ADezii
8,834 Expert 8TB
Opening a Recordset, Navigating within that Recordset, then making Edits within the Recordset, all encapsulated in a Transaction was a little tricky and Error prone. I really did not have too much time to investigate, so I took a Hybrid approach which seems to work quite well:
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdTest_Click()
  2. On Error GoTo Err_cmdTest_Click
  3. Dim strUser1 As String
  4. Dim strUser2 As String
  5. Dim strSerialNum1 As String
  6. Dim strSerialNum2 As String
  7. Dim strCriteria1 As String
  8. Dim strCriteria2 As String
  9. Dim rst As DAO.Recordset
  10. Dim wrkCurrent As DAO.Workspace
  11. Dim blnInTrans As Boolean       'Are we in a Transaction?
  12.  
  13. strUser1 = "ADezii"
  14. strSerialNum1 = "555B7"
  15. strUser2 = "NeoPa"
  16. strSerialNum2 = "KLY76"
  17.  
  18. strCriteria1 = "[User] = '" & strUser1 & "' And [SerialNum] = '" & strSerialNum1 & "'"
  19. strCriteria2 = "[User] = '" & strUser2 & "' And [SerialNum] = '" & strSerialNum2 & "'"
  20.  
  21. blnInTrans = False              'Not in a Transaction yet
  22.  
  23. 'Do PCs even exist for the Unique Combination of User/Serial Number?
  24. If DCount("*", "tblPCs", strCriteria1) > 0 And _
  25.    DCount("*", "tblPCs", strCriteria2) Then
  26.      Set wrkCurrent = DAO.DBEngine.Workspaces(0)
  27.      wrkCurrent.BeginTrans
  28.      blnInTrans = True      'Presently in a Transaction
  29.  
  30.        CurrentDb.Execute "UPDATE tblPCs SET [User] = '" & strUser2 & "' WHERE " & _
  31.                           strCriteria1, dbFailOnError
  32.        'Err.Raise 13        'Rollback Test
  33.        CurrentDb.Execute "UPDATE tblPCs SET [User] = '" & strUser1 & "' WHERE " & _
  34.                           strCriteria2, dbFailOnError
  35.     wrkCurrent.CommitTrans
  36.     blnInTrans = False      'Changes committed without an Error, Transaction is complete
  37.  
  38.     DAO.DBEngine.Workspaces(0).Close
  39. Else
  40.     MsgBox "One or both PCs do not exist for the specified combination of User and " & _
  41.            "Serial Number", vbExclamation, "Swap Aborted"
  42. End If
  43.  
  44. Exit_cmdTest_Click:
  45.   Exit Sub
  46.  
  47. Err_cmdTest_Click:
  48.   If blnInTrans Then      'Was the Transaction successfully completed, or does it need to be Rolled back?
  49.     If Not wrkCurrent Is Nothing Then wrkCurrent.Rollback
  50.   End If
  51.     If Not wrkCurrent Is Nothing Then
  52.       DAO.DBEngine.Workspaces(0).Close: Set wrkCurrent = Nothing
  53.     End If
  54.     MsgBox Err.Description, vbExclamation, "Error in cmdTest_Click()"
  55.       Resume Exit_cmdTest_Click
  56. End Sub
Sep 25 '11 #18
NeoPa
32,556 Expert Mod 16PB
Actually, it seems it is possible to handle this with a single SQL update query. Assuming the code is run from a Command Button - cmdSwap - found on the form then the code could be :
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdSwap_Click()
  2.     Dim strSQL As String
  3.  
  4.     strSQL = "UPDATE [tblUserPC] " & _
  5.              "SET    [UserName] = IIf([UserName] = '%UN1', '%UN2', '%UN1') " & _
  6.              "WHERE  (([UserName] = '%UN1')" & _
  7.              "  AND   ([PC] = '%PC1'))" & _
  8.              "   OR  (([UserName] = '%UN2')" & _
  9.              "  AND   ([PC] = '%PC2'))"
  10.     With Me
  11.         strSQL = Replace(strSQL, "%UN1", .UserName1)
  12.         strSQL = Replace(strSQL, "%UN2", .UserName2)
  13.         strSQL = Replace(strSQL, "%PC1", .Serial1)
  14.         strSQL = Replace(strSQL, "%PC2", .Serial2)
  15.         Call CurrentDb.Execute(strSQL)
  16.     End With
  17. End Sub
PS. As the updates are all carried out in a single process the requirement for transaction handling is obviated.
Sep 26 '11 #19
NeoPa
32,556 Expert Mod 16PB
Apologies to anyone trying to make sense of my previous post (#19) prior to my posting this one, for the changes I had to keep trying out in order for what I posted to show as intended. I'd originally tried to use %U1 & % U2 (sans space) as replacement parameters for the two UserName values in the SQL template, but for reasons that are unclear to me, these were automatically edited out by the content parser and the code left behind made no discernable sense. I got around it eventually by using %UN1 & %UN2, which seems to work fine. I also changed %P1 & %P2 to %PC1 & %PC2 simply for consistency.

I hope this didn't disrupt anybody, and I can confirm all seems to be correct now.
Sep 26 '11 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Ian Barnes | last post by:
I have a VB6 program that uses standard ADO 2.5 connection to read and write to an Access 97 database on a Windows 98 machine. The same program is run by a number of other people who use Windows 98...
1
by: Joe | last post by:
I have a table with a student id and course id. I would like to make both fields the primary key since a student can have multiple course ids but I do not want duplicate records. How would I go...
23
nehashri
by: nehashri | last post by:
hi i am designing a database using Ms Access and ASP. i have 3 tables in access namely 'PERSONAL', other as 'POLICY' and 3rd one is named as 'STAFF'. in the contact table i have ID, Name, Children...
2
by: RKSpangler | last post by:
Greetings: Is there any way to determine the maximum width of all data elements in a particular column in a table? Sorting a column won't do it, of course, since it will use a collating...
1
by: JCCDEVEL | last post by:
Hi All, I am working on a legacy MS Access Data Project. I have a form that displays results from a view. The user would like to be able to occasionally filter the results by a record value. ...
1
by: junis | last post by:
Dear Experts.. i need create table with identiry field .. if i use GUI ..i just click and choose autonumber as type ... but i try with SQL Stement : "Create Table Test (id autonumber, Desc...
0
by: =?ISO-8859-1?Q?Josep_M=AA_Puigdollers?= | last post by:
I'm trying to save a Date into an Access database. I'm using a dataset with only one table, and that table has only two fields: a string and a date field. My code is similar to this: strValue...
0
by: babai28 | last post by:
Hi All, I have an Access Db Table Called Employees. The columns are as follows: EmployeeId (Autonumber) PK EmployeeName (Text) EmployeeRole (Test) DateOfJoining (DateTime)
0
by: wed1 | last post by:
Hi all I was asked from the company i support their intranet with asp to create a vb prog in order to retrive magazine circulations from their oracle server and update the number of circulations...
2
by: lwannwayoo | last post by:
Hi Everybody! I have a database in Microsoft Access 2003 and I want to insert image in my Table Field. How can I don it??. I use OLE type but when i insert image to that field only the word...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
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...
1
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...
0
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...
0
marktang
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
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 using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.