Access 2010:导入使用 FileDialog 选择的 Excel 文件
Posted
技术标签:
【中文标题】Access 2010:导入使用 FileDialog 选择的 Excel 文件【英文标题】:Access 2010: Import Excel File which is selected with a FileDialog 【发布时间】:2017-01-11 10:25:14 【问题描述】:我是 Access 和 VBA 的新手。 我创建了一个表单,我可以在其中通过 fileDialog 选择一个文件。
这里是fileDialog的代码:
Public Function DateiAuswaehlen()
Dim objFiledialog As FileDialog
Set objFiledialog = _
Application.FileDialog(msoFileDialogOpen)
With objFiledialog
.AllowMultiSelect = False
If .Show = True Then
DateiAuswaehlen = .SelectedItems(1)
End If
End With
Set objFiledialog = Nothing
End Function
如何将选定的 Excel 文件导入访问表? 我找到了 DoCmd.TransferSpreadsheet 方法,但它没有用,我什至不知道在哪里放置它。对不起,我提到我对 VBA 很陌生
【问题讨论】:
您的函数 DateiAuswaehlen 将返回 excel 文件路径。所以调用这个函数后,使用 DoCmd.TransferSpreadsheet 应该很容易,我们可以你的代码说明你是如何使用它的吗? 【参考方案1】:给你!!
Sub btn_GetFileName_Click()
'************************************************************************
'Lets get the file name
Debug.Print "Getting File Name"
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Set the starting look location
Dim strComPath As String
strComPath = "C:\"
Dim strFilePath As String
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is a String,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
.InitialFileName = strComPath
.AllowMultiSelect = False
.Filters.Clear
'Add filter to only show excel files.
.Filters.Add "Excel files", "*.xlsm", 1
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the action button.
If .Show = -1 Then
strFilePath = .SelectedItems(1)
'Step through each string in the FileDialogSelectedItems collection.
'For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is a String that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example simply displays the path in a message box.
' strFilePath: " & vrtSelectedItem
'Next vrtSelectedItem
Else
'The user pressed Cancel.
DoCmd.Hourglass (False)
MsgBox "You must select a file to import before proceeding", vbOKOnly + vbExclamation, "No file Selected, exiting"
Set fd = Nothing
Exit Sub
End If
End With
tblFileName = strFilePath
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "tblTest", tblFileName, True
Set fd = Nothing
End Sub
【讨论】:
以上是关于Access 2010:导入使用 FileDialog 选择的 Excel 文件的主要内容,如果未能解决你的问题,请参考以下文章
将 MySQL 数据导入 Access 2010 时出现问题
自动将不同的 Excel 文件导入 MS Access 2010 表