导入csv文件时,为访问表添加文件名

时间:2011-12-06 15:55:24

标签: ms-access vba

我在驱动器C:上的一个主文件夹中的多个文件夹中有多个csv文件。有些文件每天都会更新。如果文件有更新,我需要将新的每日数据加载到包含文件名的访问表中。到目前为止,该脚本导入了所有csv文件中的所有数据。然后,它将文件名添加到新记录中。我需要将文件名添加到所有记录中。

非常感谢任何帮助。

脚本:

Sub 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"

End Sub

1 个答案:

答案 0 :(得分:2)

我不是100%确定问题是什么,但是如果您尝试更新刚刚导入的记录中的文件名,则可以使用简单的更新语句:

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

这里我假设该字段将为null或空字符串,但如果这不正确,您可以用自己的标准替换它。您可以使用DoCmd.RunSQL执行此操作。

如果我误解了这个问题,那么请更新你的问题以使其更清楚。

相关问题