0

我想通过 Access 表单浏览/选择数据库文件,并根据所选数据库文件的文件路径对其运行查询。我试过这样:

SELECT *
    FROM ExternalTableName IN '[Forms]![MyForm]![SelectedFilePath]'
    WHERE Condition

...但这没有用,但是这个 SQL 确实有效:

SELECT *
    FROM ExternalTableName IN 'C:\users\desktop\filename.mdb'
    WHERE Condition

为了浏览文件,我使用了这个 VBA 片段:

Private Sub cmd1()
    Dim fd As FileDialog
    Dim oFD As Variant
    Dim fileName As String

    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
        .ButtonName = "Select"
        .AllowMultiSelect = False
        .Filters.Add "Access Files", "*.mdb", 1
        .Title = "Choose Text File"
        .InitialView = msoFileDialogViewDetails
        .Show

        For Each oFD In .SelectedItems
            fileName = oFD
        Next oFD
        On Error GoTo 0
    End With

    '~~> Change this to the relevant TextBox
    Me.TextFieldName = fileName

    Set fd = Nothing
End Sub
4

1 回答 1

0

编辑:

要查询位于MDB用户从文件打开对话框中选择的表,最简单的方法(同时避免额外的引用)是这样的:

Option Explicit

Sub testQueryExternalTable()
'displays RecordCount from specified table, selected database
    Const tableName = "tblLog"
    Const defaultPath = "c:\users\" 'default path OR path+filename
    Dim rs As Recordset, fName As String, sql as String

    fName = getFileOpenDialog(defaultPath) 'get filename
    If fName = "" Then MsgBox "You clicked cancel!": Exit Sub

    sql = "select * from " & tableName & " in '" & fName & "'"
    Set rs = CurrentDb.OpenRecordset( sql ) 'query the table
    With rs
        .MoveLast 'count records
        MsgBox .RecordCount & " records found"
        .Close 'close recordset
    End With
    Set rs = Nothing 'always clean up objects when finished
End Sub

Function getFileOpenDialog(defaultPath As String) As String
'returns filename selected from dialog ("" if user Cancels)
    With Application.FileDialog(3)
        .Title = "Please select a database to query" 'set caption
        .InitialFileName = defaultPath 'default path OR path+filename
        .AllowMultiSelect = False 'maximum one selection
        .Filters.Clear 'set file filters for drop down
        .Filters.Add "All Files", "*.*" '(in reverse order)
        .Filters.Add "Access Databases", "*.mdb" '(last = default filter)
        If .Show = True Then getFileOpenDialog = .SelectedItems(1) 'show dialog
    End With
End Function

更多信息:


原答案:

使用 Access 的内置功能比在 VBA 中重新创建它更容易(也更有效)。

                                                              <sub> (点击放大图片)
 <a href="https://i.stack.imgur.com/RkRSF.png" rel="nofollow noreferrer"> 截屏  <img src="https://i.stack. imgur.com/Y9K5q.png" width="300" height="230" alt=" screenshot" title="点击放大截图"/>

一个选项 imports,第二个选项强调文本链接而不导入。链接表后,您可以在 VBA 中使用它或像本地表一样进行查询。

于 2018-03-31T12:03:09.030 回答