简体   繁体   中英

Calling the Value of a Function from within a VBA Sub

Asking users to identify the folder where they want certain files to be saved, then save new workbooks to that folder. Sub calls the Function that sets this folder path to JobFolder. When calling JobFolder folder path from sub, the sub runs the Function all over again. Just need the value of JobFolder. Thank you.

Sub ExportJobFiles()


'Ask user to set job folder

    Dim JobFolder As String
    JobFolder = GetFolder()


'Ask user to set suffix for file names

    Dim FileNameSuffix As Variant
    Dim Default As String

    Default = Worksheets("Summary").Range("E2").Value
    FileNameSuffix = InputBox("Input suffix for job files", , Default)


'Creates job files in job folder

    Dim SummaryFileName As String
    Dim AFileName As String
    Dim BFileName As String
    Dim CFileName As String

    SummaryFileName = JobFolder & "/Summary_" & FileNameSuffix & ".xls"
    AFileName = JobFolder & "/A_" & FileNameSuffix & ".xls"
    BFileName = JobFolder & "/B_" & FileNameSuffix & ".xls"
    CFileName = JobFolder & "/C_" & FileNameSuffix & ".xls"

    Workbooks.Add.SaveAs FileName:=SummaryFileName
    Workbooks.Add.SaveAs FileName:=AFileName
    Workbooks.Add.SaveAs FileName:=BFileName
    Workbooks.Add.SaveAs FileName:=CFileName

End Sub


Function GetFolder() As String

    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = ""
        .Show
        GetFolder = .SelectedItems(1)
    End With

End Function
Call JobFolder

That's calling the function (with an obsolete explicit call syntax) and discarding its return value .

Basically, that line does nothing useful .

Instead, declare a local variable:

Dim folder As String

And assign it with the function's return value:

folder = JobFolder

As noted in comments , you should also avoid GoTo jumps in or out of With blocks.

If the With block was written like this:

With Application.FileDialog(msoFileDialogFolderPicker)
    '...
End With

Then jumping out of it would leave the object reference held by the With block in limbo. The only reason that's not happening with your code is because you already have a reference to the With block variable outside the With block, and you're destroying it manually... which isn't necessary if you let the With block handle the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM