Вопрос:

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

excel vba excel-vba excel-2007 create-directory

3611 просмотра

2 ответа

13 Репутация автора

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.

Автор: brockmvendors Источник Размещён: 22.08.2016 09:39

Ответы (2)


1 плюс

48023 Репутация автора

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)
Автор: David Zemens Размещён: 22.08.2016 09:44

2 плюса

8625 Репутация автора

Решение

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

Автор: 0m3r Размещён: 22.08.2016 10:00
Вопросы из категории :
32x32