簡體   English   中英

將function選擇的文件夾復用給其他子例程

[英]Reuse folder selected by function for other sub routines

試圖澄清舊帖子。 有沒有辦法在幾個不同的子程序中調用 choosefolder function 並且每次調用時都不會彈出 window。 基本上嘗試重用最初選擇的文件夾路徑以使用該路徑運行不同的子例程。

這是找到的代碼示例。 我能夠使基礎工作,但無法將其傳遞到將調用選擇文件夾的 3 個不同子例程中。

VBA - 選擇一個文件夾並將其引用為單獨代碼的路徑

將 ChooseFolder() 變成 function 然后引用它:

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

像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM