【问题标题】:Add filename to access table while importing csv file导入 csv 文件时添加文件名以访问表
【发布时间】:2015-03-13 03:16:59
【问题描述】:

我在驱动器 C: 上的一个主文件夹中的多个文件夹中有多个 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"

结束子

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

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

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

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

    如果我对问题有误解,请更新您的问题以使其更清楚。

    【讨论】:

    • 您好,谢谢您的建议。在从“For intFile = 1 To UBound(strFileList)”开始的 fro 循环中,因为每条记录都放在访问表中,我希望将文件名放在表列“com”中。您的建议会在这个循环中起作用吗?
    • 是的,您希望文件名与每个导入的记录一起保存。 TransferText 将一次性加载整个文件(因此多条记录)。然后,您需要使用文件名更新这些记录。在循环中调用 UPDATE 语句并确保 WHERE 子句只获取最新的记录,否则您也将更新以前的记录。使用您使用的记录集代码,您正在添加另一条新记录,而不是更新现有记录。你可以在记录集中做你想做的事,但单行 DoCmd.RunSQL 语句会更简单。
    • CurrentDB.Execute SQLString, dbFailOnError 将跳过您使用DoCmd.RunSQL 获得的警告,如果您首先将 CurrentDB 分配给数据库对象并使用它,您可以获得RecordsAffected, which may be useful.
    • @Remou,好点和更好的解决方案。 Sid - 照他说的做。
    • 嗨,进度... 脚本现在使用文本文本“myfile”加载“com”列中的所有字段。如何获取数据来自字段的文件名?我尝试了带引号和不带引号的 strFile ,但这不起作用。提前很多tks。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多