使用 VBA 在 Access 中导入 txt 文件 - 日期格式问题 - 导入规范

Posted

技术标签:

【中文标题】使用 VBA 在 Access 中导入 txt 文件 - 日期格式问题 - 导入规范【英文标题】:Importing txt files in Access using VBA - date format issue - import specification 【发布时间】:2016-02-26 15:17:51 【问题描述】:

我正在导入从 Excel 导出的 txt 文件,并以一般格式结束,即 42408 等。

将其导入 Access 时,将其作为导入没有问题。 (我将数据类型设置为日期等,它可以工作 -> 没有导入错误。)

但是,当我尝试使用以下代码多重导入时,除了我收到“类型转换错误”的日期之外,所有内容都会导入。

现在,我认为问题在于导入规范。 [查看图片]

有人知道导入规范的配置可以使它工作吗?

Database file here (also I have included the import txt file)

Sub import_multiple_files()
On Error GoTo bImportFiles_Click_Err

Dim objFS As Object, objFolder As Object
Dim objFiles As Object, objF1 As Object
Dim strFolderPath As String

strFolderPath = "s:\downloads\import_files\"
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder(strFolderPath)
Set objFiles = objFolder.files

For Each objF1 In objFiles
    If Right(objF1.Name, 3) = "txt" Then
        DoCmd.TransferText acImportDelim, "TextImportSpecs", "tblImportedFiles", strFolderPath & objF1.Name, False
        Name strFolderPath & objF1.Name As "s:\downloads\Archived Files\" & objF1.Name 'Move the files to the archive folder
    End If
Next

Set objF1 = Nothing
Set objFiles = Nothing
Set objFolder = Nothing
Set objFS = Nothing

bImportFiles_Click_Exit:
Exit Sub

bImportFiles_Click_Err:
MsgBox Err.Number & " " & Err.Description
Resume bImportFiles_Click_Exit

End Sub

【问题讨论】:

【参考方案1】:

如果可以避免的话,永远不要使用字符串。

42408 只是日期值的数值。您可以使用 CDate 轻松地将其转换为数据类型 Date:

 RealDate: CDate(NumericDate)

 42408 -> 2016-02-08 

为避免以后更新和/或字段,请不要导入文件而是链接它。然后创建一个查询来读取链接表并执行所需的任何转换。

现在将此查询用作导入或进一步处理的源。

【讨论】:

yh 这会起作用,但问题是我不想添加任何额外的字段。如果我能让导入规范配置为工作,那将是最好的解决方案。 或者,OP 可以导入临时表并通过附加查询迁移到具有任何需要的转换/计算的最终表。【参考方案2】:

您可以手动导入日期列为日期的表,并将导入和代码调用保存为 DoCmd.RunSavedImportExport "Your import name"

【讨论】:

这不会做我想要的,即输入所有文件(txt 文件),而不管文件的数量或特定文件夹中的名称 我的错。这是我使用的解决方法。将日期作为字符串导入。稍后添加一列作为日期时间并更新新列 DoCmd.RunSQL "update Tablename" " set [Start_date] = datevalue(startdate)"

以上是关于使用 VBA 在 Access 中导入 txt 文件 - 日期格式问题 - 导入规范的主要内容,如果未能解决你的问题,请参考以下文章

长文本(> 255 个字符)在 MS Access 2013 中导入和添加到现有表时被截断

使用 VBA 从 Access 表中将选定的列导入 Excel

在 Access 中导入 .sql 文件

VBA从添加到工作簿中导入udf模块

我希望从 ms-access 2013 数据库中的所有表单、报告和模块中导出 vba 源代码

带有空格和范围的 MS Access VBA acImport 工作表名称