Home > Software engineering >  Reuse folder selected by function for other sub routines
Reuse folder selected by function for other sub routines

Time:11-28

Trying to get clarification on an older post. Is there a way to call the choosefolder function in several different subroutines and not have the pop up window each time it is called. Basically trying to reuse the folder path selected initially to run different subroutines using that path.

Here is a sample of the code of found. I was able to get the base to work, but can't pass it into the 3 different subroutines that would call on the choose folder.

VBA - selecting a folder and referencing it as the path for a separate code

Make ChooseFolder() into a function and then reference it:

Public Function ChooseFolder()
    Dim fldr As FileDialog
    Dim sItem As String

    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With

NextCode:
    ChooseFolder = sItem
    Set fldr = Nothing
End Function


Private Sub btn_LeaveReport()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim sFldr As String

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

sFldr = ChooseFolder()
Set objFolder = objFSO.GetFolder(sFldr)
i = 3

'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
    'print file name
    Cells(i   1, 2) = objFile.Name
    'print file path
    Cells(i   1, 3) = objFile.Path
    i = i   1
Next objFile
End Sub

CodePudding user response:

Like this:

Sub Main()
    Dim fldr As String
   
    fldr = ChooseFolder()
    If Len(fldr) > 0 Then
        PartOne fldr
        PartTwo fldr
        PartThree fldr 
    Else
        MsgBox "No folder selected"
    End If
End Sub

Sub PartOne(fldr as String)
    'use fldr
End Sub

Sub PartTwo(fldr as String)
    'use fldr
End Sub

Sub PartThree(fldr as String)
    'use fldr
End Sub
  • Related