Matt Hall
Matt Hall

Reputation: 2412

Populating field(s) in a table with values derived out of VBA code

I found some neat code (via here actually) for getting the username of the user currently logged in to Windows.

Say I have a table called AdminEntry. I'd be looking to get the AdminEntry table set up as the recordsource of a form, so the user would do the data entry on that table via the form. Any record they create and complete data entry for would then also have their username stamped on that record so we can track what belongs to who.

Not sure how I would go about pushing that username string in to the table, or the best approach.

Perhaps if the AdminEntry table had the following fields:

| UserName | Field1 | Field2 |
|          |        |        |

The user could just use the form to do data entry on Field1 and Field2:

| UserName | Field1 | Field2 |
|          |  data  |  data  |

And then an event on a Save button could perhaps pull through the username string in to the UserName field and prior to saving the full record in the AdminEntry table:

| UserName | Field1 | Field2 |
|   data   |  data  |  data  |

Haven't got a clue how to pull through that username string though, so would love some help/pointers!

Upvotes: 1

Views: 2438

Answers (1)

HansUp
HansUp

Reputation: 97101

Add a text box, txtUserName, to the form and bind it to the UserName field. You can set the text box's .Visible property to No.

Then assign the value from that fOSUserName() function to txtUserName from the form's before update event. Note before update also occurs in conjunction with form insert, so this approach will store the current user name both when you add a new record and when you modify an existing record.

Private Sub Form_BeforeUpdate(Cancel As Integer)
    ' Me.txtUserName = CreateObject("WScript.Network").UserName
    Me.txtUserName = fOSUserName
End Sub

Upvotes: 2

Related Questions