Help VBA create folders and subfolders and save file inside

Asked

Viewed 243 times

0

Good morning guys, I need help with a code in Vba, basically what I want to do and in the directory that is the Excel workbook he creates a folder called "Save"And inside this Save folder he takes what is written in cell A1 and create another folder with the name of the cell, so far all well I could do, but after he created the folder with the name of cell A1 I would like him to create inside it a folder called "info" and save the file in . txt inside the info folder. the first two folders I could but the 3rd folder and save inside it could not, someone can help me?

Sub CriarPasta()

'Cria a pasta Raiz aonde esta a pasta de trabalho
     
    Dim raiz As Object, save
        Set raiz = CreateObject("Scripting.FileSystemObject")

            On Error Resume Next

                save = ThisWorkbook.Path & "\" & "Save"

    If Not raiz.FolderExists(save) Then
            raiz.CreateFolder (save)
    End If
    
    
'Cria a pasta com o nome da celula A1 dentro da pasta Save
    
    Dim sub_p As Object, subPasta
        Set sub_p = CreateObject("Scripting.FileSystemObject")

            On Error Resume Next

                subPasta = save & "\" & Planilha1.Range("A1").Text

    If Not sub_p.FolderExists(subPasta) Then
        sub_p.CreateFolder (subPasta)
    End If

'Cria uma pasta chamada info dentro da pasta criada com o nome da celula A1

    Dim sub_p1 As Object, info_p
        Set sub_p1 = CreateObject("Scripting.FileSystemObject")

            On Error Resume Next

                sub_p1 = save & "\" & subPasta & "\" & "info"

    If Not sub_p1.FolderExists(info_p) Then
        sub_p1.CreateFolder (info_p)
    End If

'Salva em txt dentro da pasta info

    Dim Nome As String
    
    Nome = Planilha1.Range("A1").Text
    ActiveWorkbook.SaveAs Filename:=save & "\" & subPasta & "\" & info_p & "\" & Nome & ".txt", _
    FileFormat:=xlUnicodeText, CreateBackup:=False


End Sub

1 answer

1


You’re gonna have a problem here:

    sub_p1 = save & "\" & subPasta & "\" & "info"

Because some lines above you have already defined that string subpasta is the entire path of the folder with the name A1, inside the save folder. Therefore, the above statement transformed the string sub_p1 in a redundant monster, something like c:\...\save\c:\...\save\nome_a1\info. Since the subfolder string already contains the save string at the beginning, I believe it is only necessary to change the above statement to:

    sub_p1 = subPasta & "\" & "info"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.