2011-12-06 30 views
0

我在驅動器C:上的一個主文件夾中有多個文件夾中的多個csv文件。有些文件每天更新​​。如果文件有更新,我需要將新的每日數據加載到包含文件名的訪問表中。到目前爲止,該腳本從所有csv文件導入所有數據。然後它將文件名添加到新記錄中。我需要將文件名添加到所有記錄中。在導入csv文件時將文件名添加到訪問表

任何幫助將不勝感激。

腳本:

子Import_multiple_csv_files()

Const strPath As String = "C:\text1\" 'Directory Path 
Dim strFile As String 'Filename 
Dim strFileList() As String 'File Array 
Dim intFile As Integer 'File Number 
Dim rs As DAO.Recordset 
'Loop through the folder & build file list 
strFile = Dir(strPath & "*.csv") 
While strFile <> "" 
    'add files to the list 
    intFile = intFile + 1 
    ReDim Preserve strFileList(1 To intFile) 
    strFileList(intFile) = strFile 
    strFile = Dir() 
Wend 
'see if any files were found 
If intFile = 0 Then 
    MsgBox "No files found" 
    Exit Sub 
End If 
'cycle through the list of files & import to Access 
'creating a new table called MyTable 

For intFile = 1 To UBound(strFileList) 

DoCmd.TransferText acImportDelimi, , _ 
    "Test", strPath & strFileList(intFile) 
    ‘add file name to record 
    Set rs = CurrentDb.OpenRecordset("Test") 
    rs.AddNew 
    rs.Fields("Com").Value = Dir(strPath & "*") 
    rs.Update 
    rs.Close 
    Set rs = Nothing 


Next 

MsgBox UBound(strFileList) & " Files were Imported" 

末次

回答

2

我不是100%肯定的問題是什麼,但如果你試圖更新文件名中您剛剛導入的記錄可以通過簡單的更新聲明來完成:

UPDATE Test SET Com='MyFileName' WHERE Com IS NULL OR Com='' 

這裏我假設該字段將爲空或空字符串,但如果這不正確,則可以用您自己的條件替換此字段。您可以使用DoCmd.RunSQL來執行此操作。

如果我誤解了問題,請更新您的問題以使其更清晰。

+0

嗨,Tks爲您的建議。在將每個記錄放置在訪問表中的'For intFile = 1 To UBound(strFileList)'開始的循環中,我希望將文件名放置在表列'com'中。你的建議會在這個循環中起作用嗎? –

+0

是的,您希望文件名與每個導入的記錄一起保存。 TransferText將一次加載整個文件(如此多個記錄)。然後您需要用文件名更新這些記錄。在循環中調用UPDATE語句,並確保WHERE子句只選取最新的記錄,否則您將更新以前的記錄。使用您使用的記錄集代碼,您將添加另一個新記錄,而不是更新現有記錄。您可以在記錄集中執行所需操作,但單行DoCmd.RunSQL語句將更簡單。 – Simon

+0

'CurrentDB.Execute SQLString,dbFailOnError'將跳過您使用'DoCmd.RunSQL'獲得的警告,並且如果您先將CurrentDB分配給數據庫對象,並使用它,則可以獲得'RecordsAffected,這可能很有用。 – Fionnuala