Een familie van Microsoft-spreadsheetsoftware met hulpmiddelen voor het analyseren, in kaart brengen en communiceren van gegevens.
Hi Henk G,
Good day. I'm Jhun an independent advisor. In regards with your question if Environ$ ("username") works with remote desktops? The answer is YES, but with important conditions.
- Environ$("USERNAME") work on Remote desktop (RDP) when a user connects through Remote Desktop, the session still runs under their own Windows user account, so:
sUsernameWin = Environ$("USERNAME")
will return the logged-in username of the RDP sessions, not the local machine.
Example: If a remote user connects with:
Windows login on remote server: HenkG Then Environ$("USERNAME") inside Excel/VBA on that remote desktop will return: HenkG
Important Considerations:
- It returns the remote machine's username. Not the username of the local workstation. You will only get the account name used to authenticate into the remote computer.
- It works for Terminal Server, Citrix, Azure Virtual Desktop, etc. As long as the user has a Windows account, the environment variable is loaded normally.
- It can be Overridden. Environment variables can be manually changed (rare but possible). For better security, you can use:
sUsername = CreateObject("WScript.Network").UserName
This is harder to spoof. - Machine policies or domain logins may return domain prefixes.
Example:
DOMAIN\HenkG
You can strip the domain if needed:
sUser = Split(CreateObject("WScript.Network").UserName, "")(UBound(Split(...))).
If your goal is "allow only authorized users to open the file, you can combine username validation with a close-file action in Workbook_Open:
Private Sub Workbook_Open()
Dim allowedUsers As Variant
allowedUsers = Array("HenkG", "MariaS", "Admin1")
Dim sUser As String
sUser = Environ$("USERNAME")
If IsError(Application.Match(sUser, allowedUsers, 0)) Then
MsgBox "You are not authorized to use this file.", vbCritical
ThisWorkbook.Close False
End If
End Sub
I hope this helps.
Regards,
Jhun