You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA ADO读取分号分隔CSV时无法按分号拆分的问题

解决方案

方案1:修正ADO连接字符串的引号嵌套问题

你的连接字符串错误核心是Extended Properties内部的引号未正确转义——在VBA字符串中,要表示单引号需要用两个单引号('')来转义,否则OLEDB会解析出错。

修正后的完整代码:

Sub GetDatafromCSV()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    
    Set cn = New ADODB.Connection
    
    ' 修正引号转义,让OLEDB识别分号分隔符
    cn.ConnectionString = _
    "Provider=Microsoft.ACE.OLEDB.16.0;" & _
    "Data Source=" & GetLocalPath(ThisWorkbook.Path) & "\;" & _
    "Extended Properties='text;HDR=YES;FMT=Delimited('';'')'"
    
    cn.Open
    
    Set rs = New ADODB.Recordset
    ' 简化Recordset打开方式
    rs.Open "SELECT * FROM [Test.csv]", cn
    
    Tabelle2.Range("A21").CopyFromRecordset rs
    
    ' 清理资源,避免内存泄漏
    rs.Close
    cn.Close
    Set rs = Nothing
    Set cn = Nothing

End Sub

方案2:直接读取文本文件拆分(无需ADO驱动)

如果ADO方法仍有适配问题,可尝试直接读取CSV文本并按分号拆分,无需依赖OLEDB驱动,逻辑更直观:

Sub ReadCSV_Semicolon()
    Dim filePath As String
    Dim fileNum As Integer
    Dim lineText As String
    Dim splitData As Variant
    Dim rowNum As Integer
    
    ' 定义CSV文件路径
    filePath = GetLocalPath(ThisWorkbook.Path) & "\Test.csv"
    fileNum = FreeFile()
    rowNum = 21 ' 从工作表A21开始写入数据
    
    Open filePath For Input As #fileNum
    ' 跳过表头(如果不需要跳过表头,可删除此行)
    Line Input #fileNum, lineText
    
    ' 逐行读取并拆分数据
    Do Until EOF(fileNum)
        Line Input #fileNum, lineText
        splitData = Split(lineText, ";")
        ' 将拆分后的数据写入工作表
        Tabelle2.Cells(rowNum, 1).Resize(1, UBound(splitData) + 1).Value = splitData
        rowNum = rowNum + 1
    Loop
    
    Close #fileNum
End Sub

内容的提问来源于stack exchange,提问作者Pl0x_H3lp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:28:17