【发布时间】:2014-04-06 21:58:24
【问题描述】:
我需要一个访问 vba 代码来导入一个 excel 文件,但我需要用户选择哪个 excel 文件。我是访问 vba 的新手。
【问题讨论】:
我需要一个访问 vba 代码来导入一个 excel 文件,但我需要用户选择哪个 excel 文件。我是访问 vba 的新手。
【问题讨论】:
试试这个。
Sub ExcelImport()
Dim intRet_B As Integer
Dim GetTableName As String
TableName = "table name" 'Put an access table name between "".
SetFile01:
With Application.FileDialog(msoFileDialogOpen)
.Title = "Select the file" 'Title of dialog box
.Filters.Clear
.Filters.Add "Custom Excel Files", "*.xlsx, *.csv, *.xls"
.AllowMultiSelect = False
.InitialFileName = CurrentProject.Path
intRet_B = .Show
If intRet_B <> 0 Then
GetTableName = Trim(.SelectedItems.Item(1))
Else
GetTableName = ""
Answ = MsgBox("The file is not selected. If you want to select it, press Yes, No otherwise.", vbQuestion + vbYesNo + vbSystemModal, "File selection")
If Answ = vbYes Then
GoTo SetFile01
Else
MsgBox "Abort the process.", vbOKOnly + vbInformation + vbSystemModal, "Process Termination"
DoCmd.Close
DoCmd.Quit
End
End If
End If
End With
End Sub
【讨论】:
您必须打开 FileOpen 通用对话框。这将对您有所帮助:
How to show "Open File" Dialog in Access 2007 VBA?
这里是在 Excel 文件中读取的代码:
【讨论】:
我认为您需要提供更多关于您到目前为止所尝试的详细信息。但是,从以下代码开始会有所帮助。
Function File_dailog() As String
On Error GoTo catchError
txtPath = ""
Set fso = CreateObject("Scripting.FileSystemObject")
Dim directory As String, fileName As String, total As Integer
Dim fd As Object
Set fd = Application.FileDialog(3) ' this will open the file dailog
With fd ' following are the properties of the file dailog
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2010", "*.xlsx?" ' you can add more filters of the file for the users below
If .Show = True Then
txtPath = Dir(.SelectedItems(1))
End If
txtPath = fso.GetFileName(.SelectedItems(1)) ' fetching the file name
End With
File_dailog = txtPath 'return value
exit_catchError:
Exit Function
catchError:
If Err.Number = 5 Then ' error handling if nothing selected by the user
Exit Function
End If
End Function
要导入你可以使用的excel:
strTable = "temp" ' name of table you want in your database
strFile = File_Dailog ' you will get the file name from user selection
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, strTable, strFile, True
我希望这会有所帮助。
【讨论】:
这是我喜欢使用的代码:
Dim SelectedFile As String
Dim FilePicker As FileDialog
Dim SQLdelete As String
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)
FilePicker.AllowMultiSelect = False
FilePicker.Filters.Add "Excel", "*.xls*", 1
FilePicker.InitialFileName = "C:\Users\"
FilePicker.Title = "Please Select the Excel Data..."
FilePicker.Show
If FilePicker.SelectedItems.Count <> 0 Then
SelectedFile = FilePicker.SelectedItems(1)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "tbl_Name", SelectedFile, True
MsgBox ("The data has been successfully loaded")
End If
注意:tbl_Name 是您希望保存 Excel 数据的表的名称。
【讨论】: