Microsoft Access - Get UserName and store in a table - ms-access

I made a table to store which users open a database and when. I have a function to get the usernames in the VBA already since some forms are restricted.
How do I get all usernames stored in the new table along with a time stamp?
Thanks!
I want to track who uses a database, and when they login. That's it. I have a table set up to store the usernames and the timestamp for when someone opens the database
I have the code to get usernames when the database is opened, and it compares to an admin list I have in a table. That code is
Option Compare Database
Declare Function GetUserName& Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long)
Public Function UserName() As String
Dim str As String
Dim lng As Long
str = String$(200, 0)
lng = 199
If GetUserName(str, lng) Then
UserName = Left$(str, lng - 1)
End If
End Function

Create an empty form called "Splash" and make this the form that opens when you open the database (Options->Current Database->Display Form)
Put this code in the Form_Open Event. This will load the screen whenever someone opens the db, insert a record into a table called LoginRecord and then close the form. The action is invisible to the user. Adjust the table/field names in the code to fit your situation.
Private Sub Form_Load()
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO LoginRecord (UserName, LoginTime) VALUES ('" & Environ("Username") & "','" & Now() & "')"
DoCmd.Close acForm, "Splash"
DoCmd.SetWarnings True
End Sub

Related

Unable to filter datasheet form after inserting value in ms access

I am using a datahseet subform in my main form for the realtime view of entries added in the table via the main form. This subform filters data on load event and checks with users windows username and compares it with data, it should only show data of respective owner. That means it willl filter the name field and shows only the entries made by the respective user(to unable users to edit each other's entries). It works well with the below code which I used in this datasheet form's vba :
Option Compare Database
Option Explicit
Dim GetUserName As String
Dim GetEmpID As String
Dim RecCount As String
Public Sub GetValues()
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
RecCount = DCount("[ID]", "Mau_con", "[AdvisorName] = '" & GetUserName & "'")
Set obj1 = Nothing
End Sub
Private Sub Form_AfterInsert()
Call Form_Load
End Sub
Private Sub Form_Load()
Call GetValues
If RecCount > 0 Then
Dim strOpen As String
strOpen = "[AdvisorName] = '" & GetUserName & "'"
Me.Filter = strOpen
Me.FilterOn = True
Me.Recordset.MoveLast
End If
End Sub
It filters the data on load but problems arises when a new user comes and login, then it will skip the if loop and will work normally, I tried to requery the form after making first entry by the new user & I also tried to call form_load in after insert event but both did not work.
But it filters the data once we close it and reopen it.
What is the best way to overcome this ?
Please ask if any other information needed.
Thanks in Advance.

How to record unbound control to a database

I have a form control (address) that uses Dlookup to call info from a table "database" but the form is bound to table "Tracker". The dlookup is based on another control on the same form - "Name" I need the form to record this dlookup control, along with other controls that are bound to "tracker" as new recordto the table "tracker."
My failed attempts:
Using the default value property to assign the recalled data from the dlookup to another text box which would be bound to "tracker" This simply does not work for some reason. Perhaps I am missing something that tells this control "Address" to update upon selecting the correct "name?"
Code:
Private Sub SubmitReferral_Click()
On Error GoTo Err_SubmitReferral_Click
DoCmd.GoToRecord , , acNewRec
Exit_SubmitReferral_Click:
Exit Sub
Err_SubmitReferral_Click:
MsgBox Err.Description
Resume Exit_SubmitReferral_Click
End Sub
I also tried this - to assign the data - but the data from the dlookup in control "Address1" is not transferring/copying to control "Address2"
Private Sub Combo276_OnUpdate()
OnUpdate ([Address2].Value = [Address1].Value)
End Sub
Help or suggestions?
PS - I have tried to Edit per request to be as specific as possible, and to follow proper board etiquette.
Still unsure of your field names, etc., but the following is an example you can modify. Change 'tblEmployee' to 'database'.
I must state that if you are just starting out with developing in Access (or VBA) that you should never use names that are reserved words, or that can be misleading. Your table named 'database' is ok if named 'tblDatabase'.
Option Compare Database
option Explicit
Private Sub cmdInsert_Click()
Dim strSQL As String
Dim i As Integer
Debug.Print "cmdInsert; "
i = MsgBox("Do you want to add 1 row for Employee ID: " & Me.EmpID & " to table 'tracker'?", vbYesNo, "Confirm Add")
If i = vbNo Then
Exit Sub
End If
DoCmd.SetWarnings True
strSQL = "INSERT INTO tracker ( FirstName, LastName, Add1, City, St, Zip ) " & _
"SELECT tblEmployee.FirstName, tblEmployee.LastName, tblEmployee.Add1, tblEmployee.City, tblEmployee.St, tblEmployee.Zip " & _
"FROM tblEmployee " & _
"WHERE (((tblEmployee.EmpID)=" & Me.EmpID & "));"
DoCmd.RunSQL strSQL
End Sub
Thanks for the help - I solved my concern by hiding the fields that contain the dlookup, and putting code behind a button that copies the information to fields that are bound and therefore will record to the table "tracker"

Track user changes in MS Access

I have a table and a Form in MS Access. Data is added through the Form. I want to be able to track user changes. I have a column User in my table where the user name will be added after update of the Form. For this purpose I have the following VBA code which will be fired After Update of the form, however it doesnt work and I dont know where the mistake is. Help will be appreciated. Thanks
Private Sub Form_AfterUpdate()
Dim UserLogin As String
Dim MyId As Integer
Dim strSQL As String
Dim rs As Recordset
UserLogin = Environ("Username")
MyId = Me!ID.Value
Set strSQL = "Update [MyTable] SET [MyTable]!User = '" & UserLogin & "' WHERE [MyTable]!ID = '" & MyId & "';"
'Set rs = dbs.OpenRecordset(strSQL)
DoCmd.RunSQL strSQL
You can track changes not only in particular form, but any change made in data will be registered, even if it was done directly on table. Just create Before Change data macro for your table ("Create Data Macro" menu in table design mode.
In Data Macro designer add the action SetField with parameters: Name = User ("User" is your field name for storing user name) and Value = GetUserName().
In any standard module create the function like this:
Public Function GetUserName() As String
GetUserName = Environ("Username")
End Function
After this any change in your table will update changed record by name of user, who did this change.
Please note, in case of split database this function should be available in front end and in back end databases if you want to edit data also in backend.
As of your code, check data type of ID field. If it's Number, remove single quotes. Also replace "!" by "." in SQL query text.
Just insert a textbox with controlsource as "User"
and then instead of after update use
Private Sub Form_BeforeUpdate()
me.user = Environ("Username")
end sub
no need for separate SQL operation

database search via username

I'm developing a call log system, and for tracking purposes the manager wants each user to be logged in upon entry.
I have a module that displays the current logged on user with the code below. I would like for the system to search the table "TBL_Users" for the username and in the text boxes display all the information pertinent to that username. Should that user not be in the database i need to display an error and not allow the user to progress into the system. I'm aware i may need to use a Dlookup but I'm unsure how to code this.
Option Compare Database
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function fOSUserName() As String
' Returns the network login name
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If (lngX > 0) Then
fOSUserName = Left$(strUserName, lngLen - 1)
Else
fOSUserName = vbNullString
End If
End Function
After playing around with Dlookup for a while, I need the text-boxes to populate on form load. This is the Dlookup i used.
Private Sub Form_Load()
Windows_Logontxt = fOSUserName()
'agentname = DLookup("Agent_Name", "TBL_Users", "Windows_Logon=" & Windows_Logontxt)
End Sub
It seems Windows_Logon and Windows_Logontxt are text values, so enclose Windows_Logontxt in quotes when you create the string for the third argument to DLookup.
DLookup("Agent_Name", "TBL_Users", "Windows_Logon='" & Windows_Logontxt & "'")

Adding a row to a table with data from report?

Right now, I've got a database that allows a user to create a basic report based on a query from a table using a parameter. Pretty straightforward. What I want to do now is to use VBA to add a record into a separate table every time a report is created. Each report has the information from the query PLUS some new information (concatenated IDs, dates, etc.). The new table ("Summary") would include some of that new information plus a few sources from the original query. It would be sort of a dynamic log of reports created.
Is there any way to use VBA to combine data from the two sources (data displayed on report from original query and native report data) into one record on a table?
Here's the code I've got so far.
Option Compare Database
Public Sub Log_Report()
'System definitions
Dim dbs As DAO.database
Dim rs As DAO.Recordset
Dim rep As [Report_Custom MARS Report]
'Original report sources
Dim Text267 As String
Dim TableName As String
Dim Company_Name As String
Dim ReportID As String
'Summary table destination
Dim ID As Integer
Dim Date_Created As Date
Dim Source As String
Dim Title As String
Dim report_ID As String
Dim Attachment As Attachment
End Sub
I'm probably way off, so if I have to start over, I'm fine with that. I'm no expert in VBA by any means, so it's been a lot of trial and error so far.
I can clarify if needed.
If the record set for your report is a single row, it would be relatively easy to use the on load event to read the fields and assign them to variables. All of the calculations have been done by the time your Report_Load event fires and you could then use them as inputs to a function which writes the values to your summary table.
'Code to placed in a public function
'strVar = text267 'is ReportID = report_ID ?
'Unfortunately I have no experience with attachments, sorry
function writeReportSummary(intID as Integer, dtmDate_Created as Date, strSource as String, strTitle as string, strReportID as string, strVar as string, strTableName as string, strCompanyName as string, attAttachment as attachment) AS boolean
Dim strSQL as string
On error goto Err_Handler
strSQL = "INSERT INTO summary( ID, Date_Created, Source, Title, report_ID, Text267, tableName, Company_Name, ReportID) SELECT """ & intID & """ , """ & dtmDate & """;" 'etc
CurrentDb.execute strSQL, dbFailOnError
Debug.print CurrentDB.recordsAffected & ": Record(s) Inserted at " & now()
writeReportSummary = True
Exit function
Err_Handler:
debug.print err.number
debug.print err.description
writeReportSummary = false
end function
'Code to be placed in Report_load'
Sub Report_Load
if Not(writeReportSummary(intID, dtmDate, etc)) then debug.print "Failed to write report to summary table"
End Sub