vba - 使用 FileDialog 选择文件名

标签 vba ms-access

我正在尝试使用 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: 部分

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

   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

关于vba - 使用 FileDialog 选择文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626449/

相关文章:

excel - 根据标题查找列然后格式化行

xml - 使用 Google 地理编码 API 进行 VBA 编程

文本框中的VBA文本字符串限制

excel - 如何过滤范围并复制到不同工作表中的表格底部?

excel - 从一系列文档模板生成Word文档(在Excel VBA中)

java - 如何使用java中的sql查询列出MS Access数据库文件中的所有表名称?

sql - 插入 INTO NOT EXISTS SQL Access

sql - MS Access 2003 中 IN 子句中的元组

java - 除非使用完整路径,否则找不到合适的驱动程序

vba - 外文字符显示为??????在VBA 2003中,如何设置UTF-8?