从VBA Sub中调用函数的值

时间:2017-01-27 19:27:24

标签: vba excel-vba excel

要求用户识别他们希望保存某些文件的文件夹,然后将新工作簿保存到该文件夹​​。 Sub调用将此文件夹路径设置为JobFolder的Function。从sub调用JobFolder文件夹路径时,sub再次运行Function。只需要JobFolder的价值。谢谢。

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

1 个答案:

答案 0 :(得分:1)

Call JobFolder

调用该函数(使用过时的显式调用语法)并丢弃其返回值

基本上,该行没有任何用处

相反,声明一个局部变量:

Dim folder As String

并使用函数的返回值赋值:

folder = JobFolder

作为noted in comments,您还应该避免GoTo跳入或跳出With块。

如果With块的写法如下:

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

然后跳出它将使With块保持的对象引用处于不确定状态。您的代码没有发生的唯一原因是因为您已经With块之外引用了With块变量,并且您正在手动销毁它。 。这不是必需的如果你让With块处理引用。