访问VBA - 导入*.CSV时出现运行时错误31519。您无法导入此文件。

5
在使用Access中的DoCmd.TransferText方法时,我遇到了问题标题中描述的错误。我的代码从当前数据库的表中获取文件名(这些文件是来自单个文件夹中大约2000个文件中选择的文件),其目标是将这些文件的内容导入Access中的一个表中。请参阅以下主题以获取更多信息:VBA procedure to import only selected csv files (from one folder) into a single table in access 所有文件具有相同的结构和数据类型。enter image description here 以下是我正在使用的代码:
 Sub Importing_data_into_a_single_table_csv_version()
   Dim my_path As String
   Dim rs As Recordset
   Dim start As Double
   Dim total_time As String

     DoCmd.SetWarnings True
     my_path = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_csv\"     ' source folder.

     start = Timer         ' remember time when macro starts.

     Set rs = CurrentDb.OpenRecordset("CSV Files")   ' opens the table with file names.
       Do Until rs.EOF
          If Dir(my_path & rs.Fields(0).Value) <> "" Then
          ' DoCmd.TransferText acImportDelim, "macro_link_specification", "all_stocks_3", "my_path & rs.Fields(0).Value", True
             DoCmd.TransferText acImportDelim, "import", "all_stocks_1", "my_path & rs.Fields(0).Value", True
          ' expression. TransferText ( TransferType, SpecificationName, TableName, FileName, HasFieldNames, HTMLTableName, CodePage )

          End If
          rs.MoveNext
       Loop

   total_time = Format(Timer - start, "hh:mm:ss")
   MsgBox "This code ran successfully in " & total_time, vbInformation
 End Sub

代码在DoCmd.TransferText acImportDelim, "import", "all_stocks_1", "my_path & rs.Fields(0).Value", True处崩溃。 enter image description here 导入这些文件时,目标表需要进行特殊准备吗?对不起问这种问题,但我现在只是一个初学者,才用了三周的Access。 我使用了名为“import”的导入规范。这可能是问题的原因吗?
这是目标表的样子: enter image description here 这是另一个我一直试图导入数据的表。 该表中的字段名称没有特殊字符,并且已在字段上设置相同的数据类型,但并没有任何区别。仍然返回相同的错误31519。 enter image description here

1
首先,请确保您能够使用标准的“外部数据”->“导入Access”,使用存储的规范导入文本。我认为问题在规范上。首先检查十进制分隔符。此外,尝试重命名列标题,特殊字符有时可能会引起问题。 - Sergey S.
你可能需要暂时将文件从.mst重命名为.csv才能导入。对于这些事情,Access可能会有些棘手。 - Andre
@Andre 是的,Andre,谢谢您的建议。与以前的问题相关的代码已经稍作修改。我尽了最大努力排除一些愚蠢的错误。这段代码仅适用于从“CSV文件”链接表中获取名称的*.CSV文件 :-) 我只是不明白为什么手动加载这些文件时,一个接一个地加载到表中时,会出现这个错误。 - michal roesler
1
等等,"my_path & rs.Fields(0).Value" 是你实际的代码吗?你必须去掉引号,这样变量才能被使用。DoCmd.TransferText acImportDelim, "import", "all_stocks_1", my_path & rs.Fields(0).Value, True - Andre
@Andre 我现在正在检查您的建议。有点道理。错误已经改变,但数据仍然无法加载到Access表中。我需要一些时间来弄清楚,并会回复您。 - michal roesler
@Andre 你好,Andre。请将此评论作为答案编写,以便我将其标记为正确答案。从DoCmd.TransferText方法的FileName参数中删除引号是修复代码的关键,现在它正在工作。谢谢你,我的朋友。 - michal roesler
1个回答

1
解决方案很简单:

DoCmd.TransferText acImportDelim, "import", "all_stocks_1", _
                   "my_path & rs.Fields(0).Value", True

文件名变量应该在引号内,这样它才能被识别为字符串(并且提供有效的路径)。

正确写法:

DoCmd.TransferText acImportDelim, "import", "all_stocks_1", _
                   my_path & rs.Fields(0).Value, True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接