Share via


How to: Display the Current User's Logon ID in a Cell

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Document-level projects

  • Application-level projects

Microsoft Office version

  • Excel 2003

  • Excel 2007

For more information, see Features Available by Application and Project Type.

You can read the current user's logon ID by using the GetCurrent method of the WindowsIdentity object to represent the current user. You can then display the user's logon ID in a named range on a Microsoft Office Excel worksheet.

To display text in cell, use a NamedRange control or a native Excel range object.

Using a NamedRange Control

This example is for document-level customizations. The following code must be placed in a sheet class, not in the ThisWorkbook class.

To display the current user's logon ID in a named range

  1. Get the user's logon ID.

    Dim user As System.Security.Principal.WindowsIdentity
    user = System.Security.Principal.WindowsIdentity.GetCurrent()
    
    System.Security.Principal.WindowsIdentity user;
    user = System.Security.Principal.WindowsIdentity.GetCurrent();
    
  2. Create a NamedRange control named userID and display the user's login ID.

    Dim userID As Microsoft.Office.Tools.Excel.NamedRange
    userID = Me.Controls.AddNamedRange(Me.Range("A1"), "userID")
    
    userID.Value2 = user.Name
    
    Microsoft.Office.Tools.Excel.NamedRange userID;
    userID = this.Controls.AddNamedRange(this.Range["A1", missing], "userID");
    
    userID.Value2 = user.Name;
    

Using a Native Excel Range

To display the current user's logon ID in a native Excel range

  1. Get the user's logon ID.

    Dim user As System.Security.Principal.WindowsIdentity
    user = System.Security.Principal.WindowsIdentity.GetCurrent()
    
    System.Security.Principal.WindowsIdentity user;
    user = System.Security.Principal.WindowsIdentity.GetCurrent();
    
  2. Create a Range named userID and display the user's login ID.

    Dim userID As Excel.Range = Me.Application.Range("A1")
    
    userID.Value2 = user.Name
    
    Excel.Range userID = this.Application.get_Range("A1", missing);
    
    userID.Value2 = user.Name;
    

Robust Programming

The following conditions might cause an exception:

See Also

Tasks

How to: Refer to Worksheet Ranges in Code

How to: Create a WindowsPrincipal Object

Concepts

Working with Cells

The Variable missing and Optional Parameters in Office Solutions