I can't return a variable from a function and use it as a condition

Brass Contributor

Good Morning
I want to create a file in a directory, but only if that directory already exists. If it does not exist, it returns a message warning that the directory does not exist.
I am not able to do the function and I would like help to understand the correct way to do it.

Thanks.

 

Sub Inicio()
        if V_Dir("C:\Users\" & Environ("username") & "\OneDrive\Matriz","Não existe")= "Existe" Then
              With Workbooks.Add
                     .SaveAs "C:\Users\" & Environ("username") & "\OneDrive\Matriz\DIARIAS_BDadosAux.xls"
                     ThisWorkbook.Worksheets("BD COLAB").Range("A:A").Copy Destination:=Workbooks("DIARIAS_BDadosAux.xls").Worksheets("Folha1").Range("A:A")
             End With
        Else
              MsgBox "A Directoria para ser colocado o ficheiro a ser usado pelas Diárias, não existe !!!"
        End If
End Sub


Function V_Dir(strFolderName As String, strTextoMensagem) As String
      strFolderExists = Dir(strFolderName, vbDirectory)
      If strFolderExists = "" Then
          MsgBox strTextoMensagem
          V_Dir= "Existe"
          Exit Function
      End If
End Function

1 Reply

Try this version:

Sub Inicio()
    Dim strFolder As String
    strFolder = "C:\Users\" & Environ("username") & "\OneDrive\Matriz"
    If V_Dir(strFolder, "Não existe") = "Existe" Then
        With Workbooks.Add
            ThisWorkbook.Worksheets("BD COLAB").Range("A:A").Copy Destination:=.Worksheets(1).Range("A:A")
            .SaveAs strFolder & "\DIARIAS_BDadosAux.xls"
        End With
    Else
        MsgBox "A Directoria para ser colocado o ficheiro a ser usado pelas Diárias, não existe !!!"
    End If
End Sub

Function V_Dir(strFolderName As String, strTextoMensagem) As String
    If Dir(strFolderName, vbDirectory) = "" Then
        MsgBox strTextoMensagem
    Else
        V_Dir = "Existe"
    End If
End Function