Home » excel » Excel communicate with SQL Server to identify user.

Excel communicate with SQL Server to identify user.

Posted by: admin May 14, 2020 Leave a comment


Excel queries SQL Server. Trying to query using current user name. I have an Excel file that queries a view in SQL Server. The view is set to return the results based on the user querying the view.

I setup a file on a network server for others to access, hoping that when they opened the file, it would show only the information relating to them.

But the information still only refers to myself. I want it to show information the user using the file, as if they were querying the view directly.

Here is the sample query for the view:

Select * from dbo.WorkEstimate where Estimator = SUSER_NAME()

But the Excel sheet only returns the information relating to myself. I think it may have something to do with the connectstring that always specifies my workstation name. Is there a way to change that to reflect the individual (or their workstation) that is using the file?

How to&Answers:

The SUSER_NAME() (transact-sql) in the SQL statment refers to the current user within the context of the currently executing SQL statement. In your case, it is the userID you specified in your connection string. The sql server uses that user specified in your connectionstring to run that statement and thus your SUSER_NAME() reflect that user.

You will need to specify the user that the Excel is running under (Windows environment) with the following Excel functions:

  • Application.Username is the name of the User set in Excel Tools>Options (under the User Name box)
  • Environ("Username") is the name you registered for Windows see Control Panel >System

So, your SQL statement will have have to be something like:

vsSQL = "SELECT * FROM dbo.WorkEstimate WHERE (Estimator = '" & Environ("Username") & "');"

Hope this helps.


You don’t need to have Excel communicate with SQL Server to figure that out. Excel needs to communicate with the user’s machine.

Use this code to discover all of the environment variables that pertain to the user logged in to the machine. Look through the results to figure out what you need to pass in to your query.

Add a module to your Excel file and paste in the following:

Sub ListAllEnvironmentVariables()
    Dim ws As Worksheet
    Dim rng As Range

    Set ws = Sheets("Sheet1")
    Set rng = ws.Range("A1")

    Dim i As Integer
    i = 1
    Do Until Environ$(i) = ""
        rng.Offset(i - 1).Value = Environ(i)
        i = i + 1
End Sub

I’m using Sheet1 in my example, but you can change that and set ws to any blank sheet in your workbook to see how it works. Obviously don’t use Sheet1 if you have data on the sheet.

<a href="https://exceptionshub.com/category/sql-server”>More Answers>