brockmvendors
brockmvendors

Reputation: 23

Create a folder in any user's Desktop directory if it does not exist

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:

  1. See if the folder exists already or not, and if it exists open the folder
  2. Create the folder if it does not already exist, and open it after creating

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

Answers (2)

0m3r
0m3r

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

VBA Environ

Upvotes: 2

David Zemens
David Zemens

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

Related Questions