如何将变量值从一个模块返回到另一个模块?

时间:2015-07-02 03:25:45

标签: vba excel-vba excel

第一个模块..

Public Sub Directory_Path()
Dim Directory As String
    Directory = InputBox("Enter the Directory path that contains folders ""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
    If Right(Directory, 1) = "\" Then
    Directory = Left(Directory, Len(Directory) - 1)
    End If
End Sub

我使用Public Sub Directory_Path()调用了第二个模块中的第一个模块。我希望第一个模块中的Directory变量用作第二个模块中的变量...帮助我。我想念一些......如果重复这个问题,请回答我,我会删除这篇文章。

1 个答案:

答案 0 :(得分:1)

最明显的解决方案是让它成为一个功能......

Public Function Directory_Path() As sting
    Dim Directory As String
    Directory = InputBox("Enter the Directory path that contains folders " & _
                """This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
    If Right(Directory, 1) = "\" Then
        Directory_Path = Left(Directory, Len(Directory) - 1)
    Else
        Directory_Path = vbNullString
    End If
End Function

...然后调用函数:

Debug.Print Directory_Path

请注意,您无需要求用户键入路径,而是可以使用FileDialog:

Public Function Directory_Path() As String
    Dim prompt As FileDialog
    Set prompt = Application.FileDialog(msoFileDialogFolderPicker)
    With prompt
        .Title = "Select Directory path that contains folders " & _
                 """This Quarter"",""Last Quarter"",""Second_Last_Quarter""."
        .AllowMultiSelect = False
        If .Show <> 0 Then Directory_Path = .SelectedItems(1)
    End With
End Function