Udostępnij za pośrednictwem


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

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.

Applies to: The information in this topic applies to document-level projects and application-level projects for Excel 2007 and Excel 2010. For more information, see Features Available by Office Application and Project Type.

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

Optional Parameters in Office Solutions