Inserting the Window username into MS Word file

A

appeng

Currently I have a document that hase a line as follows;
Printed by username, on date, at time.
Where the username, date, and time are fields inserted by way of Words menu
Insert > Field.

For the username, I would like to the Windows Login Username rather than the
username from Word.

Can you provide an example of VBA code I can use?

The document currently has the following
Sub FileOpen()
'
Dialogs(wdDialogFileOpen).Show
Selection.Fields.Update
End Sub


We are using both Word 2003 and 2007.
 
G

Graham Mayor

Change the user field to a docvariable field and populate it with the
following

Dim oVars As Variables
Set oVars = ActiveDocument.Variables
oVars("varUser").Value = Environ("Username")
ActiveDocument.Fields.Update


--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 
D

David Horowitz

I might use something like this:
Selection.TypeText Environ("USERNAME")
It uses the environment variable USERNAME (which you can see at a command
prompt if you use the SET command).
There are API calls you can make, but I believe this works just as well.
David
 
K

Karl E. Peterson

appeng said:
For the username, I would like to the Windows Login Username rather than the
username from Word.

Can you provide an example of VBA code I can use?

If you're rather not trust the somewhat volatile environment variables,
you can go straight to the source:

Private Declare Function GetUserName Lib "advapi32.dll" Alias
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Private Const UNLEN As Long = 256 ' Maximum username length

Private Function CurrentUserName() As String
Dim Buffer As String
Dim nLen As Long
Const NameLength = UNLEN + 1
Buffer = Space$(NameLength)
nLen = Len(Buffer)
If GetUserName(Buffer, nLen) Then
CurrentUserName = Left$(Buffer, nLen - 1)
End If
End Function
 
A

appeng

This did the job thank you.


Graham Mayor said:
Change the user field to a docvariable field and populate it with the
following

Dim oVars As Variables
Set oVars = ActiveDocument.Variables
oVars("varUser").Value = Environ("Username")
ActiveDocument.Fields.Update


--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>






.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top