GetUserName help

C

Chris

I am a complete newbie to VBA. I want to use the advapi.dll call below
method below to compare the network username to restrict access to the
workbook: If it is possible, I would rather use the API than the
"Environ" for security reasons. Is it possible to do this?

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

Function UserNameWindows() As String

Dim lngLen As Long
Dim strBuffer As String

Const dhcMaxUserName = 255

strBuffer = Space(dhcMaxUserName)
lngLen = dhcMaxUserName
If CBool(GetUserName(strBuffer, lngLen)) Then
UserNameWindows = Left$(strBuffer, lngLen - 1)
Else
UserNameWindows = ""
End If
End Function

TO COMBINE WITH THE BELOW NOT USING THE ENVIRON METHOD.

Private Sub Workbook_Open()
Application.ScreenUpdating = False
FrontpageFirst
x = Environ("username")
On Error Resume Next
Select Case x
Case "pmason"
Worksheets("Summary").Visible = True
Worksheets("Key to Abbrvs").Visible = True
Worksheets("Open Positions").Visible = True
Worksheets("Filled Positions").Visible = True
Worksheets("Temp to Hires").Visible = True
Case Else
For i = 2 To Worksheets.Count
Worksheets(i).Visible = xlVeryHidden
Next
End Select
Worksheets(2).Activate
Worksheets(1).Visible = xlVeryHidden
Application.ScreenUpdating = True
End Sub

Sub FrontpageFirst()
Dim page As String
page = "Unauthorized"
On Error Resume Next
Worksheets(page).Visible = True
If Worksheets(1).Name = page Then
Worksheets(1).Activate
Else
Worksheets(page).Activate
If Err = 0 Then
ActiveSheet.Move before:=Worksheets(1)
Else
Worksheets.Add before:=Worksheets(1)
Worksheets(1).Name = page
End If
End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
FrontpageFirst
For i = 2 To Worksheets.Count
Worksheets(i).Visible = xlVeryHidden
Next
Application.DisplayAlerts = True
ActiveWorkbook.Save
Application.DisplayAlerts = False
End Sub
 
B

Bob Phillips

Just change the

x = Environ("UserName")

to

x = UserNameWindows


--
HTH

Bob Phillips

(replace somewhere in email address with gmail if mailing direct)
 
C

Chris

Thanks!


Bob said:
Just change the

x = Environ("UserName")

to

x = UserNameWindows


--
HTH

Bob Phillips

(replace somewhere in email address with gmail if mailing direct)
 

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