从CSV导入数据到Excel

时间:2018-10-31 13:14:47

标签: excel vba excel-vba

我有一个重复的过程,其中包括将数据从不同的csv文件导入到excel

当前过程 从数据中手动导入数据>从文本中>选择所需文件>选择定界符,并且我的数据具有标题>选择定界符逗号>下一个>完成>新工作表

有没有一种制作vba脚本/宏的方法,该脚本会提示用户他们要导入的文件并选择我选择的选项

感谢和问候

2 个答案:

答案 0 :(得分:1)

这是我前一段时间使用的一些代码。

Dirlocal.csv文件的路径

我将数据导入名为“ ODK”的工作表中

Dim ws As Worksheet
Dim strText As String

 ' read utf-8 file to strText variable
 With CreateObject("ADODB.Stream")
    .Open
    .Type = 1  ' Private Const adTypeBinary = 1
    .LoadFromFile DirLocal
    .Type = 2  ' Private Const adTypeText = 2
    .Charset = "utf-8"
    strText = .ReadText(-1)  ' Private Const adReadAll = -1
End With
' parse strText data to a sheet
Set ws = Worksheets("ODK")
intRow = 1
Application.DisplayAlerts = False
For Each strLine In Split(strText, Chr(10))
    If strLine <> "" Then
        With ws
            .Cells(intRow, 1) = strLine
            .Cells(intRow, 1).TextToColumns Destination:=Cells(intRow, 1), DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
                Semicolon:=False, Comma:=True, Space:=False, Other:=False
        End With

        intRow = intRow + 1
    End If
Next strLine
Application.DisplayAlerts = True
ReadUTF8CSVToSheet = ws.Name

答案 1 :(得分:0)

您可以使用Application.getopenfilename选择要打开的文件。 正如其中一条评论中提到的那样,使用宏记录器获取操作数据的代码是一个很好的开始,您可以将其添加到此代码中。

Sub Button1_Click()
    Dim s, wb As Workbook
    s = Application.GetOpenFilename("CSV Files (*.csv),*.csv", , "Please select CSV file...")
    If s <> False Then
        Set wb = Workbooks.Open(s)
        MsgBox "Code to Do something here"
        wb.Close False
    Else: MsgBox "Nothing Selected"
    End If



End Sub
相关问题