MS Access: Capture SystemID and Username - VBA

I had a task of calling SQL Server Stored Procedure from Access VBA. Multiple users should be able to call it. Also I had to track who is Executing the Stored procedure from Access. This code can capture SystemID and Username. These two entities can be passed as parameters to the SQL Server Stored Procedure.
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal IpBuffer As String, nSize As Long) As Long
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long

Function ThisUserName() As String
Dim LngBufLen As Long
Dim strUser As String

strUser = String$(15, " ")
LngBufLen = 15

If GetUserName(strUser, LngBufLen) = 1 Then
ThisUserName = Left(strUser, LngBufLen - 1)
Else
ThisUserName = "Unknown"
End If
End Function

Function ThisComputerID() As String
Dim LngBufLen As Long
Dim strUser As String

strUser = String$(15, " ")
LngBufLen = 15

If GetComputerName(strUser, LngBufLen) = 1 Then
ThisComputerID = Left(strUser, LngBufLen)
Else
ThisComputerID = 0
End If
End Function
Paste the above code in MS Access module as shown in below screenshot.


You can call the SQL Server Stored Procedure in this way
Dim Usrname As String
Dim UserSysNo As String
Call ThisUserName
Usrname = ThisUserName

Call ThisComputerID
UserSysNo = ThisComputerID

    Set cnn = New ADODB.Connection
    cnn.CommandTimeout = 0
    cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=192.168.0.222;Initial Catalog=yourdatabase;User ID=yourid;Password=yourpassword"
    cnn.Open
    Set rs = New ADODB.Recordset
    Set rs = cnn.Execute("EXEC YOUR_SP " & Usrname & " , " & "'" & UserSysNo & "'")
    Set rs = Nothing
    cnn.Close

No comments:

Post a Comment