excel 将函数选择的文件夹重新用于其他子例程

chhkpiq4  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(130)

试图澄清一个旧的帖子。有没有办法在几个不同的子程序中调用choosefolder函数,而不是每次调用时都弹出窗口。基本上是试图重用最初选择的文件夹路径来运行使用该路径的不同子程序。
下面是found的代码示例。我可以让base工作,但不能将它传递到3个不同的子例程中,这些子例程将调用choose文件夹。
VBA - selecting a folder and referencing it as the path for a separate code
使ChooseFolder()成为函数,然后引用它:

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
jjhzyzn0

jjhzyzn01#

就像这样:

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

相关问题