如何使用 @ as a a s a a a a s DeLimiter的VBA导入CSV文件



我正在尝试使用adodb中的VBA中的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

如果我使用逗号,它可以正常工作,但是最后,我将必须使用由'@'@'符号分开的文件,并且我不能转换为使用','由于缺少写入权限。
不幸的是,在其他地方复制和更改文件也不是一个选项。

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

'@'不支持作为划界字符串?还是我错过了什么?

感谢@siddharthrout的解决方案以及Windows Dev Center的线程的链接。

问题在于,在连接字符串中,一个人无法设置划界字符串,而只能指定使用特定字符界定文件。FMT=Delimited(@)FMT=DelimitedFMT=Delimited(,)相同。

我必须在文件夹中创建一个文件 schema.ini ,其中包含CSV-File( data.txt ),其中我必须输入:

[data.txt]
Format = Delimited(@)

schema.ini文件将被解析,并且定界符正确读取,并且一切都起作用(只要我不更改任何文件名)

我还在MSDN找到了另一个来源,该消息源说明了如何设置界定字符串(使用注册表或上述 schema.ini ),还包括TABSTOPS和固定的长度分离的文件。

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

最新更新