Environ$("username") bij remote desktop

Henk G 220 Reputatiepunten
2025-11-23T06:18:36.33+00:00

Ik wil van een bestand uitsluitend toegang geven aan door mij geregistreerde gebruikers.

Plan is om gebruik te maken van:

sUsernameWin = Environ$("username")

sUsernameMac = Environ("USER")

Aan de hand hiervan kan ik in het bestand de namen opnemen van degenen die het bestand mogen gebruiken.

Werkt Environ$("username") ook bij remote desktops?

Microsoft 365 en Office | Excel | Overige | Windows
0 opmerkingen Geen opmerkingen

Antwoord geaccepteerd door vraagauteur
Jhun Buala 6,320 Reputatiepunten Onafhankelijke adviseur
2025-11-23T07:27:17.62+00:00

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.

  1. 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

Was dit antwoord nuttig?

0 opmerkingen Geen opmerkingen

0 extra antwoorden

Sorteren op: Oudste

Uw antwoord

Antwoorden kunnen worden gemarkeerd als 'Geaccepteerd' door de auteur van de vraag en 'Aanbevolen' door moderators, zodat gebruikers het antwoord van de auteur kunnen weten.