2017-01-20 8 views
0

エクセルファイルをアクセステーブルにインポートするコードを記述しました。各ファイルをインポートすると、ファイル名が記録され、「FilesDownloaded」という別のテーブルに保存されます。アクセステーブルの値を検索するVBA

ファイルをインポートする前に、ファイル(myfile)の名前が 'FilesDownloaded'テーブルに既に保存されているかどうかを確認するvbaコードを追加します。これにより、同じファイルが2回インポートされるのを防ぐことができます。

コード:

Function Impo_allExcel() 
Dim myfile 
Dim mypath 
Dim que As Byte 
Dim rs As DAO.Recordset 


que = MsgBox("This proces will import all excel items with the .xls in the folder C:\MasterCard. Please make sure that only the files you want imported are located in this folder. Do you wish to proceed?", vbYesNo + vbQuestion) 
If que = 7 Then 
    Exit Function 
Else 
    'do nothing and proceed with code 
End If 

DoCmd.SetWarnings (False) 

DoCmd.RunSQL "DELETE * FROM tblMaster_Import;" 


MsgBox "Please WAIT while we process this request" 



mypath = "C:\Master\" 
ChDir (mypath) 
myfile = Dir(mypath & "*.xls") 



Do While myfile <> "" 
    If myfile Like "*.xls" Then 
    'this will import ALL the excel files 
    '(one at a time, but automatically) in this folder. 
    ' Make sure that's what you want. 
    'DoCmd.TransferSpreadsheet acImport, 8, "tblMasterCard_Import", mypath & myfile 
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "tblMaster_Import", mypath & myfile, 1 

    Set rs = CurrentDb.OpenRecordset("FilesDownloaded") 
    rs.AddNew 
    rs.Fields("Filename").Value = myfile 
    rs.Update 
    rs.Close 
    Set rs = Nothing 

    End If 
    myfile = Dir() 
Loop 




'append data to tblAll (risk of duplicates at this point) 
DoCmd.RunSQL "INSERT INTO tblAll SELECT tblMaster_Import.* FROM tblMaster_Import;" 

DoCmd.OpenQuery "qryUpdateDateField", acViewNormal 
''this code will apend to an existing table and runs the risk of doubling data. 
DoCmd.SetWarnings (True) 

MsgBox "Your upload is complete" 

End Function 
+0

インポートするファイルにIDがありますか?おそらく、重複を避けるためにテーブルにプライマリキーを設定できますか? –

答えて

0

可能な解決策は、名前があなたのファイルと同じであるという条件で、表FilesDownloadedにあなたの行の結果を与えるクエリを作ることです。次のようなものがあります。

countString = "SELECT COUNT(*) FROM [FilesDownloaded] WHERE [NAMEOFCOL] = " & myFile 

次に、クエリが実行され、結果が1より大きい場合は、明らかにそれがあります。

+0

私は次のようにコードを入力しました:Do While myfile <> "" countString = "[ファイル名] = myfile"からのCount(*)の選択 myfileのように "* .xls"とcountString =不一致エラーメッセージ。助けて? – Mwes

+0

クエリを実行して結果を取得する必要があります。見てみましょうhttp://stackoverflow.com/questions/23992226/how-to-save-the-result-of-a-sql-query-into-a-variable-in-vbaとhttps://msdn.microsoft .com/en-us/library/office/ff194626.aspx – Vityata

関連する問題