How to use MkDir with variable path for different users

淺唱寂寞╮ 提交于 2021-01-29 12:51:54

问题


I have a code where you input information in an excel list. I want to be able to create a folder - I am using the code below. The issue is that I want it to work for all my colleagues (not just me). Can someone please help find where I am getting an error? Note this is a partial code, the error is happening on the MkDir line. Thanks for your help in advance!

Dim Startupfolder As String
Startupfolder = Startup_Name.Value

MkDir Environ$("Userprofile") & "\nc Dropbox\investment oportunities\ & "Startupfolder"

回答1:


The problem is where you put your quotes. Try this:

MkDir Environ$("Userprofile") & "\nc Dropbox\investment oportunities\" & Startupfolder

Startupfolder is variable, so you don't want that within quotes

More info
If your folder is put in a not yet existing folder, it will fail. It will also fail if it already exists.

Try this instead:

Sub MakeDir()
    CreateFolder Environ$("Userprofile") & "\nc Dropbox"
    CreateFolder Environ$("Userprofile") & "\nc Dropbox\investment oportunities"
    CreateFolder Environ$("Userprofile") & "\nc Dropbox\investment oportunities\" & Startupfolder
End Sub

Sub CreateFolder(Folder)
    If Len(Dir(Folder, vbDirectory)) = 0 Then
        MkDir Folder
    End If
End Sub



回答2:


I would use an API Call like that

Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" ( _
  ByVal lpPath As String) As Long

and then you could call it like that

    MakeSureDirectoryPathExists Environ$("Userprofile") & _
         "\nc Dropbox\investment oportunities\" & Startupfolder & "\"

For a documentation look here resp here. Important as pointed out in the comments

If the final component of the path is a directory, not a file name, the string must end with a backslash character.



来源:https://stackoverflow.com/questions/55100123/how-to-use-mkdir-with-variable-path-for-different-users

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!