Consulting

Results 1 to 3 of 3

Thread: IF Else statement not executing properly

  1. #1
    VBAX Regular
    Joined
    Nov 2022
    Posts
    7
    Location

    IF Else statement not executing properly

    Hi All, how can the code be amend below so that subfolderpath folder will be created? Currently, if folderpath exist but subfolderpath does not exist, it kind of jump straight to End If.

    I tried to include an ElseIf, it still doesn't work.

    The code as follows:

    If Dir(folderpath, vbDirectory) = "" And Dir(subfolderpath, vbDirectory) = "" Then         
       'check whether folder exist
       MkDir folderpath        
       'create folder
       MkDir subfolderpath        
       'create folder
          If Dir(subfolderpath, vbDirectory) = "" Then
            MkDir subfolderpath        
            'create folder
           counter = counter + 1
        End If
    End If
    If Dir(folderpath, vbDirectory) = "" And Dir(subfolderpath, vbDirectory) = "" Then         
       'check whether folder exist
       MkDir folderpath        
       'create folder
       MkDir subfolderpath        
       'create folder
       ElseIf Dir(subfolderpath, vbDirectory) = "" Then
       MkDir subfolderpath        
       'create folder
       counter = counter + 1
    End If
    Last edited by Aussiebear; 12-07-2022 at 04:50 AM. Reason: Reduction of whitespace

  2. #2
    Moderator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,197
    Location
    This is because within the first If statement both of the folders need to not exist before it fires any of the rest of the code. I would imagine you need to break those two parts seperated by the 'And' into their own If's.

    So:
    If folderpath does not exixst then
    'Make both folderpath and subfolderpath
    ElseIf subfolderpath does not exist the
    'Make only subfolderpath
    Else
    'Something else

    Untested code:
    If Dir(folderpath, vbDirectory) = "" Then
        MkDir folderpath
        MkDir subfolderpath
    ElseIf Dir(subfolderpath, vbDirectory) = "" Then
        MkDir subfolderpath
    Else
        'something else
    End If
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved
    Click here for a guide on how to upload a file with your post

    Excel 365, Version 2403, Build 17425.20146

  3. #3
    VBAX Regular
    Joined
    Nov 2022
    Posts
    7
    Location
    thanks for help! it works perfectly!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •