【问题标题】:How to import a csv file using @ as delimiter with VBA如何使用@作为VBA的分隔符导入csv文件
【发布时间】:2014-02-26 20:32:38
【问题描述】:

我正在尝试使用 ADODB 使用 VBA 从 Excel 中的 csv 文件加载数据。
我有一个函数可以返回一个 Connection 对象。

Private Function OpenConnection(dataSource As String) As ADODB.Connection
    Set OpenConnection = CreateObject("ADODB.Connection")

    With OpenConnection
        .ConnectionTimeout = 5
        .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataSource & ";" & _
            "Extended Properties=""Text;HDR=YES;FMT=Delimited(,)"";Persist Security Info=False"

        Debug.Print "trying to connect: " & .ConnectionString
        .Open
    End With
End Function

然后我只打印数据。

Public Sub Test_Import()
    Dim conn As ADODB.connection, records As ADODB.Recordset

    Set connection = OpenConnection(foldername)
    Set records = connection.Execute("Select * from data.txt")

    Debug.Print records.Fields(0)
End Sub

如果我使用逗号,它可以正常工作,但最后我将不得不使用由 '@' 符号分隔的文件,并且我无法使用 ',' 因为缺少写权限。
不幸的是,在其他地方复制和更改文件也不是一种选择。

现在我在函数OpenConnection 中将FMT=Delimited(,) 更改为FMT=Delimited(@),而不是返回第一列值a1,而是返回整行a1@b1@c1

'@' 不支持作为分隔字符串吗?还是我错过了什么?

【问题讨论】:

  • 看看THIS有没有帮助?
  • @SiddharthRout:谢谢,它有效。我会尽快添加答案。

标签: excel vba csv adodb


【解决方案1】:

感谢@SiddharthRout 的解决方案和a thread at windows dev center 的链接。

问题是在连接字符串中不能设置分隔字符串,只能指定文件使用特定字符分隔。 FMT=Delimited(@) 的处理方式与 FMT=DelimitedFMT=Delimited(,) 相同。

我必须在包含我必须输入的 csv 文件 (data.txt) 的文件夹中创建一个文件 schema.ini

[data.txt]
Format = Delimited(@)

schema.ini 文件将被解析,分隔符被正确读取,一切正常(只要我不更改任何文件名)

我还找到了another source at msdn,它解释了如何设置分隔字符串(使用注册表或提到的 schema.ini),还包括制表位和固定长度的分隔文件。

【讨论】:

    【解决方案2】:

    @marcw - 你太棒了。 为了帮助你们更多 - 你不必手动创建这个文件。 如果您使用 Filedialog,它可能如下所示:

    Set fldr = Application.FileDialog(msoFileDialogOpen)
    
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False       ' Select only 1 file
        .InitialFileName = strPath      ' File location
        If .Show <> -1 Then Exit Sub    ' Quit when user cancels
        myFolder = .SelectedItems(1)
    End With
    
    'you can find below function on stackoverflow
    strPath = Left(myFolder, Len(myFolder) - Len(GetFilenameFromPath(myFolder)) - 1) 'file path ended with \
    nejm = GetFilenameFromPath(myFolder) 'file name
    
    'this is the place which is creating that "ini" file
    Open strPath & "\" & "schema.ini" For Output As #1
    Print #1, "[" & nejm & "]" & vbNewLine & "Format = Delimited(;)"
    Close #1
    

    在所有过程之后你可以添加:

    Kill strPath & "\" & "schema.ini"
    

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 2021-11-19
      相关资源
      最近更新 更多