【问题标题】:Select filename using FileDialog使用 FileDialog 选择文件名
【发布时间】:2016-02-25 11:49:36
【问题描述】:

我正在尝试使用 MS Access VBA 中的文件对话框获取完整路径和文件名。

我想要做的是通过调用此函数在按钮单击时打开文件对话框。此函数应返回从文件对话框中选择的完整路径和文件名。

我评论了循环部分,因为我只想选择单个文件。

这个函数在我选择一个文件后返回错误Error: 0

到目前为止,这是我的代码。

任何人都可以找出问题所在?

谢谢

Public Function SelectTheFile() As String

On Error GoTo SelectTheFile_ErrorHandler

        Dim fDialog As Office.FileDialog
        Dim varFile As Variant

        Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

        With fDialog

            .AllowMultiSelect = False
            .Title = "Please select one file"

            If .Show = True Then
                'For Each varFile In .SelectedItems
                   'SelectTheFile = varFile
                   'Debug.Print SelectTheFile
                'Next
                SelectTheFile = .SelectedItems(1)
                Debug.Print SelectTheFile
            Else
                Debug.Print "Cancel"
            End If
        End With

SelectTheFile_ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)

End Function

【问题讨论】:

  • 您只是在SelectTheFile_ErrorHandler: 之前缺少Exit Function,因此代码一直运行到最后。而且我认为你不需要Set fd = Nothing

标签: vba ms-access


【解决方案1】:

无论文件对话框结果如何,您的代码始终会到达 SelectTheFile_ErrorHandler: 部分

你必须在该部分之前退出函数

   Public Function SelectTheFile() As String

    On Error GoTo SelectTheFile_ErrorHandler

            Dim fDialog As Office.FileDialog
            Dim varFile As Variant

            Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

            With fDialog

                .AllowMultiSelect = False
                .Title = "Please select one file"

                If .Show = True Then
                    'For Each varFile In .SelectedItems
                       'SelectTheFile = varFile
                       'Debug.Print SelectTheFile
                    'Next
                    SelectTheFile = .SelectedItems(1)
                    Debug.Print SelectTheFile
                Else
                    Debug.Print "Cancel"
                End If
            End With

            Exit Function '<==== exit here, otherwise code goes on to following section 

    SelectTheFile_ErrorHandler:
        Set fDialog = Nothing
        MsgBox "Error " & Err & ": " & Error(Err)

    End Function

【讨论】:

    【解决方案2】:

    尝试使用这个:

    Application.GetOpenFilename
    

    这对我有用,无需实际打开文件即可保存完整的文件路径。除非我错过了您要执行的操作,否则要简单得多。在文档中阅读更多信息:https://msdn.microsoft.com/en-us/library/office/ff834966.aspx

    【讨论】:

    • 这真的很有帮助。我想说这也解决了我的问题,但我决定将答案授予下一个答案,因为他确实解释了为什么我会收到错误并同时解决问题。但我不得不承认,如果我事先知道这种方法,我应该使用它而不是我现在拥有的。非常感谢!
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多