用户选择的文件目录访问VBA

时间:2016-06-14 16:48:54

标签: vba access-vba ms-access-2010

我目前正在使用以下代码将包含excel文件的文件夹导入Access。我想将宏导出到其他人,但是使用硬编码路径对其他人不起作用。但我不知道如何改变接受用户输入的路径我想尝试制作类似文件浏览器的东西但不确定如何。

Dim otable As DAO.TableDef
Dim strPathFile As String, strFile As String, strpath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean

' accept excel first line as headers for tables
blnHasFieldNames = True

' Path to files
strpath = "C:\Users\MyName\Desktop\Test\"


strFile = Dir(strpath & "*.xls")

'import all files within selected folder
Do While Len(strFile) > 0
strPathFile = strpath & strFile
strTable = Left(strFile, Len(strFile) - 5)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
    strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop

以下是我尝试更改的内容虽然我发出错误“object''Applicationog'object_'Application'失败了”并且我不确定我是否正在使用此错误。

strpath = Application.FileDialog(msoFileDialogFilePicker)

1 个答案:

答案 0 :(得分:2)

感谢HansUp帮助解决这个问题。

选择文件夹并上传文件夹中的所有文件都在...

Const msoFileDialogFolderPicker As Long = 4
Dim objfiledialog As Object
Dim otable As DAO.TableDef
Dim strPathFile As String, strFile As String, strpath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean

' accept excel first line as headers for tables
blnHasFieldNames = True

'select folder and set path
Set objfiledialog = Application.FileDialog(msoFileDialogFolderPicker)

With objfiledialog
.AllowMultiSelect = False
If .Show Then
 strpath = .SelectedItems(1) & Chr(92)
 End If
End With

strFile = Dir(strpath & "*.xls")

'import all files within selected folder
Do While Len(strFile) > 0
strPathFile = strpath & strFile
strTable = Left(strFile, Len(strFile) - 5)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
    strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
相关问题