Reputation: 23
I have a file which, among other things, opens a specific folder when a button is pressed. I will be distributing this file to other users so the code must know to look at the correct directory to:
So far, here is the pertinent section of my code:
If Dir("C:\Users\myUsername\Desktop\sampleFolder", vbDirectory) = "" Then
MkDir "C:\Users\myUsername\Desktop\sampleFolder"
retVal = Shell("explorer.exe C:\Users\myUsername\Desktop\sampleFolder", vbNormalFocus)
Else
retVal = Shell("explorer.exe C:\Users\myUsername\Desktop\sampleFolder", vbNormalFocus)
End If
My main issue is that I can't figure out how to get a user's actual username that would appear in the file path "C:\Users__________\Desktop"
Is this even the right methodology? The code works if I insert my own username into the code, but I can't figure out the way to get the username automatically so the code is easy on the end user.
Upvotes: 2
Views: 7706
Reputation: 12499
Try
Public Sub EnsureDesktopFolderExists(ByVal folderName As String)
Dim path As String
path = Environ$("USERPROFILE") & "\Desktop\" & folderName
If Len(Dir(path, vbDirectory)) = 0 Then MkDir path
End Sub
Upvotes: 2
Reputation: 53653
My main issue is that I can't figure out how to get a user's actual username that would appear in the file path "C:\Users__________\Desktop"
Generally, the Environ
function should work (although there are probably exceptions), and you can condense the code a bit, too:
Dim username$
Dim myFolder$
username = ENVIRON("username")
myFolder = "C:\Users\" & username & "\Desktop\sampleFolder"
If Dir(myFolder, vbDirectory) = "" Then
MkDir myFolder
End If
retVal = Shell("explorer.exe " & myFolder, vbNormalFocus)
Upvotes: 1