vba 将 CSV 导入 Excel - 自动“文本到列”和“插入表格”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8701044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:48:40  来源:igfitidea点击:

Import CSV to Excel - automatically "Text to columns" and "insert table"

excelvbacsv

提问by Sune

I'd like to open my CSV (comma-delimited) file on Excel 2010 and automagically convert text to columns and then select all active cells and insert table with headers.

我想在 Excel 2010 上打开我的 CSV(逗号分隔)文件并自动将文本转换为列,然后选择所有活动单元格并插入带有标题的表格。

Is it possible to add a button to my ribbon that would do all this for me?

是否可以在我的功能区中添加一个按钮来为我完成所有这些工作?

I quite often work with CSV files with different sizes and I find it to be bit of a pain to do this manually each time.

我经常使用不同大小的 CSV 文件,我发现每次手动执行此操作有点麻烦。

回答by Kevin Pope

A bit late for this, but I just ran across the question...

有点晚了,但我刚刚遇到了这个问题......

This is for selecting specific files from a picker:

这是用于从选择器中选择特定文件:

Sub OpenCSV()
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = True
    fd.Show
    For Each fileItem In fd.SelectedItems
        Workbooks.OpenText Filename:= _
            fileItem _
            , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
            xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
            Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
    Next
End Sub

This will open all CSV files in a chosen folder:

这将打开所选文件夹中的所有 CSV 文件:

Sub OpenCSVFolder()
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    fd.AllowMultiSelect = True
    fd.Show
    For Each folderItem In fd.SelectedItems
        fileItem = Dir(folderItem & "\" & "*.csv")
        While fileItem <> ""
            Workbooks.OpenText Filename:= _
                folderItem & "\" & fileItem _
                , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
                xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
                Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
            fileItem = Dir
        Wend
    Next
End Sub

Note that these files are set to Tab Delimited- change the delimiter by updating the Tab:=Trueor Comma:=Falseparameters.

请注意,这些文件设置为Tab Delimited- 通过更新Tab:=TrueComma:=False参数更改分隔符。