Excel VBA Check if directory exists error

后端 未结 7 930
别那么骄傲
别那么骄傲 2020-12-01 10:34

I have a spreadsheet that upon clicking a button will duplicate itself by copying/pasting everything to a new workbook and save the file with a name that is dependent upon s

相关标签:
7条回答
  • 2020-12-01 10:47

    To check for the existence of a directory using Dir, you need to specify vbDirectory as the second argument, as in something like:

    If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then
    

    Note that, with vbDirectory, Dir will return a non-empty string if the specified path already exists as a directory or as a file (provided the file doesn't have any of the read-only, hidden, or system attributes). You could use GetAttr to be certain it's a directory and not a file.

    0 讨论(0)
  • 2020-12-01 10:47

    To be certain that a folder exists (and not a file) I use this function:

    Public Function FolderExists(strFolderPath As String) As Boolean
        On Error Resume Next
        FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
        On Error GoTo 0
    End Function
    

    It works both, with \ at the end and without.

    0 讨论(0)
  • 2020-12-01 10:48

    Use the FolderExists method of the Scripting object.

    Public Function dirExists(s_directory As String) As Boolean
        Dim oFSO As Object
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        dirExists = oFSO.FolderExists(s_directory)
    End Function
    
    0 讨论(0)
  • 2020-12-01 10:51

    I ended up using:

    Function DirectoryExists(Directory As String) As Boolean
        DirectoryExists = False
        If Len(Dir(Directory, vbDirectory)) > 0 Then
            If (GetAttr(Directory) And vbDirectory) = vbDirectory Then
                DirectoryExists = True
            End If
        End If
    End Function
    

    which is a mix of @Brian and @ZygD answers. Where I think @Brian's answer is not enough and don't like the On Error Resume Next used in @ZygD's answer

    0 讨论(0)
  • 2020-12-01 10:52

    You can replace WB_parentfolder with something like "C:\". For me WB_parentfolder is grabbing the location of the current workbook. file_des_folder is the new folder i want. This goes through and creates as many folders as you need.

            folder1 = Left(file_des_folder, InStr(Len(WB_parentfolder) + 1, file_loc, "\"))
            Do While folder1 <> file_des_folder
                folder1 = Left(file_des_folder, InStr(Len(folder1) + 1, file_loc, "\"))
                If Dir(file_des_folder, vbDirectory) = "" Then      'create folder if there is not one
                    MkDir folder1
                End If
            Loop
    
    0 讨论(0)
  • 2020-12-01 11:05
    If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
       MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
    End If
    
    0 讨论(0)
提交回复
热议问题