首页 > 解决方案 > Excel 宏导入 CSV 数据失败,TextFileParseType

问题描述

我正在尝试使用以下代码将 CSV 数据从 URL 加载到我的 MS Excel 工作表中:

Sub LoadCSVData()
    Dim sSheetName As String
    sSheetName = "Sheet1"

    ActiveWorkbook.Sheets(sSheetName).UsedRange.ClearContents

    With ActiveWorkbook.Sheets(sSheetName).QueryTables.Add(Connection:= _
        "URL;https://sampledomain.com/mydata.csv" _
        , Destination:=Sheets(sSheetName).Range("$A$1"))
        .TextFileParseType = xlDelimited
        .TextFileCommaDelimiter = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .Refresh BackgroundQuery:=False
    End With

End Sub

它抛出

错误:1004 应用程序定义或对象定义错误

TextFileParseType在与和的线上TextFileCommaDelimiter。当我将它们注释掉时,宏可以工作,但所有内容都加载到A1单元格中并且没有被解析。

知道如何解决吗?

标签: excelvba

解决方案


这几乎是Excel QueryTables 的副本。从 URL Comma Delimited 添加

将“URL”更改为“TEXT”这是我对代码的快速修改:

Sub LoadCSVData()
    Dim sSheetName As String
    sSheetName = "Sheet1"
    Dim myTable As QueryTable
    ActiveWorkbook.Sheets(sSheetName).UsedRange.ClearContents

Set myTable = ActiveWorkbook.Sheets(sSheetName).QueryTables.Add(Connection:= _
        "TEXT;http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv" _
        , Destination:=Sheets(sSheetName).Range("$A$1"))

    With myTable
        .TextFileCommaDelimiter = True
        .TextFileParseType = xlDelimited
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .Refresh BackgroundQuery:=False
    End With

End Sub

推荐阅读