如何使用一个文件对话框功能设置多个目录

时间:2018-01-31 12:52:17

标签: excel vba excel-vba

我正在使用函数在Excel中使用FileDialog设置数据库目录,但是我必须设置大约20个不同的数据库目录

我用SettingsSheet.databaseDirectory0 = sItem设置其中一个,但对于其他人,我不想为每个人写相同的功能是不是没有 参数解决方案将它们设置为一个函数?

Function GetFolder() As String
    Dim fdo As FileDialog
    Dim sItem As String
    Set fdo = Application.FileDialog(msoFileDialogFolderPicker)
    With fdo
        .Title = "Select a Directory"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
        SettingsSheet.databaseDirectory0.Value = sItem 
    End With
NextCode:
    GetFolder = sItem
    Set fdo = Nothing
End Function

2 个答案:

答案 0 :(得分:1)

将控制权交给他。有点像这样:

Function GetFolder(txt As Control) As String
    Dim fdo As FileDialog
    Dim sItem As String
    Set fdo = Application.FileDialog(msoFileDialogFolderPicker)
    With fdo
        .Title = "Select a Directory"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
        txt.Value = sItem 
    End With
NextCode:
    GetFolder = sItem
    Set fdo = Nothing
End Function

这个伪代码演示了如何使函数通用。看看我如何将控件传递给函数,然后引用它而不是databaseDirectory0

答案 1 :(得分:1)

您可以将sItem返回给父调用者并设置

SettingsSheet.databaseDirectory0n.Value = functionName(txt as Control)

这有意义吗?