我想通过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
答案 0 :(得分: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中重新创建更容易(也更有效)。
第一个选项导入,秒选项强调文字链接而不导入。表格链接后,您可以在VBA或查询中使用它,就好像它是本地表格一样。