使用 VBA 导入分号分隔的 CSV 文件而不重命名为 txt

Import semicolon separated CSV file using VBA without rename to txt

这不是重复的,因为我想要一个不包含将文件重新格式化为 txt 的解决方案:

我的目的是使用分号作为分隔符打开一个 csv 文件。为此,我使用了以下代码:

Sub prueba2()


Dim sfile As String
Dim wb As Workbook
Dim Path As String
Dim Namefile As String


Path = "V:\evfilesce9i9\apps9\vbe9\dep4\KFTP\KFTP001D_FicherosCeca"
Namefile = "\QryCECARFSECTORIAL0239*.txt"


Set wb = Workbooks.Open(Filename:=Path & Namefile, Delimiter:=";")

End Sub

当我尝试时,它是使用逗号作为分隔符打开的,而不是我指定的逗号(分号)

我在其他问题中了解到,这在 post 2006 Excel 版本中是正常的,最快的解决方案是将文件重新格式化为 txt。

这不符合我的需要,因为我必须在不改变格式的情况下进行。我找不到任何解决方案。

有人可以帮我吗?

请参阅 MS 文档 here

我想你想使用 Format 参数,而不是 delimiter 参数。

尝试:

Set wb = Workbooks.Open(Filename:=Path & Namefile, Format:=4)

似乎只有当 Format 设置为 6 时才使用 Delimiter 参数,这表示自定义分隔符。分号是标准分隔符。

编辑:

嗯...所以,这似乎是 Excel/VBA 一段时间以来一直很棘手的事情。

经过更多研究,"Format" 选项可能仅在打开 .txt 文件时使用。这就是为什么 "reformat file to .txt" 是一种可能的解决方案。

但是,有些事情是可以做的。

如果文件的第一行是:

Excel 将很好地处理打开分号分隔的文件

sep=;

我知道你说你不能重新格式化文件,但你可以这样做吗?

如果没有,我接下来建议的是:1) 使用 Open Statement to open your file and then write it to a temporary file (perhaps as a .txt), to be reopened with the original Workbooks.Open(Format:=4), or 2) write your own text importer. A sample text importer can be found in this Whosebug 页面。

Sub ImportCSVFile(filepath As String)
    Dim line As String
    Dim arrayOfElements
    Dim linenumber As Integer
    Dim elementnumber As Integer
    Dim element As Variant

    linenumber = 0
    elementnumber = 0

    Open filepath For Input As #1 ' Open file for input
        Do While Not EOF(1) ' Loop until end of file
            linenumber = linenumber + 1
            Line Input #1, line
            arrayOfElements = Split(line, ";")

            elementnumber = 0
            For Each element In arrayOfElements
                elementnumber = elementnumber + 1
                Cells(linenumber, elementnumber).Value = element
            Next
        Loop
    Close #1 ' Close file.
End Sub