如何使用VBA导入一个@作为分隔符的csv文件

5

我正在尝试使用ADODB和VBA从Excel中的CSV文件加载数据。
我有一个用于返回连接对象的函数。

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'@'不支持作为定界字符串吗?或者我错过了什么?

7
看看这个链接是否有帮助:THIS - Siddharth Rout
@SiddharthRout:谢谢,它有效。 我很快会添加答案。 - marcw
2个回答

5
感谢@SiddharthRout提供的解决方案和Windows开发中心论坛上的帖子链接。
问题在于,在连接字符串中不能设置分隔字符串,只能指定文件使用特定字符进行分隔。 FMT = Delimited(@)FMT = DelimitedFMT = Delimited(,)一样处理。
我必须在包含csv文件(data.txt)的文件夹中创建一个名为schema.ini的文件,并在其中输入:
[data.txt]
Format = Delimited(@)

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

我还在msdn的另一个来源中找到了说明如何设置分隔字符串(使用注册表或上述的schema.ini)以及包括制表符和固定长度分隔文件的内容。


1

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

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