2016-06-14 16 views
1

私は現在、以下のコードを使用してAccessにExcelファイルのフルフォルダをインポートしています。マクロを他の人にエクスポートしたいのですが、ハードコーディングされたパスで他の人にはうまくいきません。しかし、私はどのようにファイルエクスプローラのように何かをしようとしたいが、どのようにしたいのユーザー入力を受け入れるようにパスを変更するか分からない。以下はユーザーが選択したファイルディレクトリ

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_'Applicationのメソッド 『のFileDialog』」のエラーを与えられ、私は間違ってこれを使用していた場合にわからないのですけれども、私が変更しようとしているものです。

strpath = Application.FileDialog(msoFileDialogFilePicker) 
+2

は私たちに 'Application.FileDialog'を使用して失敗したコードを表示してください。ここでは、[Application.FileDialog(msoFileDialogFolderPicker)](http://stackoverflow.com/a/15906899/77335)を使用したAccess VBAの動作例です – HansUp

+0

新しいマクロを作成してリンクを試しましたが、メソッド 'filedialog' of object_'Application 'failed " – Rukgo

+0

あなたはAccessマクロまたはAccess VBAについて話していますか? – HansUp

答えて

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 
+1

いいね、ルッコ。 'Len(strpath)> 0'を確認して、' FileDialog'でユーザーが "Cancel"をクリックしたときにコードの残りの部分を試みないようにすることをお勧めします。 – HansUp

関連する問題