如何将Workbooks.Open()命令应用于VBA中的.csv文件?

时间:2016-03-29 09:16:36

标签: excel vba excel-vba csv

我列出目录中的所有.csv文件,逐个打开它们并应用“Text To Columns”,然后将每个文件保存为.xlsx。 为了打开我使用的文件:

Workbooks.Open (directory & fileName)

目录是:

directory = wb.Sheets("Directory").Cells(1, 2).Value 

和filename是一个变量。

我注意到:当Workbooks.Open (directory & fileName)命令打开文件时,即使在将“文本添加到列”之前,.csv文件也会显示它在列中分割的内容(而不是将所有内容放入列中)一栏)。 有没有办法在Workbooks.Open (directory & fileName)中定义任何文件必须以.csv?

打开

由于

3 个答案:

答案 0 :(得分:1)

请尝试按照参数作为链接。 关键点是分隔符是,或;

workbooks.Open(Filename, [UpdateLinks], [ReadOnly], [Format], [Password], [WriteResPassword], [IgnoreReadOnlyRecommended], [Origin], **[Delimiter]**, [Editable], [Notify], [Converter], [AddToMru], [Local], [CorruptLoad])

来自www.safaribooksonline.com

答案 1 :(得分:0)

您可以尝试这样来读取数据"原样"从文本文件,包括csv,并将其写入Excel工作簿:

Function MM_OpenTextFile(vPath As String, delim As String) As Variant 

    Dim FF As Integer 
    Dim lineArray As Variant 
    Dim temp As String 
    Dim arrayList As Object 

    Set arrayList = CreateObject("System.Collections.ArrayList") 

    FF = FreeFile 

    Open vPath For Input As #FF 
    While Not EOF(FF) 
        Line Input #FF, temp 
        lineArray = Split(temp, delim) 
        arrayList.Add lineArray 
        Erase lineArray 
    Wend 
    Close #FF 

    MM_OpenTextFile = WorksheetFunction.Transpose(WorksheetFunction.Transpose(arrayList.ToArray())) 

    arrayList.Clear 

    Set arrayList = Nothing 

End Function

这会将分隔文件的内容作为2D数组分配给变体,然后可以将其放置在工作表中的分隔状态,如下所示:

Sub Example() 

    Dim ar As Variant '// Must be a Variant to work

    '// Change to a file and delimiter of your choosing...
    ar = MM_OpenTextFile("C:\Users\BloggsJ\SomeFile.txt", ";")          

    '// Change 'A1' to the cell you want the data pasting to 
    With Range("A1").Resize(UBound(ar, 1), UBound(ar, 2)) 
        .NumberFormat = "@" '// Change format to "text"
        .value = ar '// insert array values
    End With 

End Sub 

答案 2 :(得分:-1)

问题在于您的Windows设置,它会根据列表分隔符自动拆分单词。您可以在Windows中更改列表separtor设置,并尝试将csv作为普通excel打开。

you can change the List separator setting in the Regional and Language Options as specified on the

    1.  Click the Windows Start menu.
    2.  Click Control Panel.
    3.  Open the Regional and Language Options dialog box.
    4.  Click the Regional Options Tab.
    5.  Click Customize / Additional settings (Win10).
    6.  Type a new separator in the List separator box.
    7.  Click OK twice.