【问题标题】:Importing data from csv to excel将数据从csv导入excel
【发布时间】:2018-10-31 13:14:46
【问题描述】:

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

当前进程 从数据手动导入数据>从文本>选择所需文件>选择分隔,我的数据有标题>选择分隔符逗号>下一步>完成>新工作表

有没有办法制作一个 vba 脚本/宏来提示用户他们想要导入什么文件并选择我选择的选项

感谢和问候

【问题讨论】:

  • 宏记录器应该给你一个好的开始:)
  • 听起来可能是 powerquery 的工作。将其设置为从文件夹加载。将源文件放在该文件夹中。

标签: excel vba


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用 Application.getopenfilename 选择要打开的所需文件。 正如其中一个 cmets 所述,使用宏记录器获取代码来操作数据是一个好的开始,您可以将其添加到此代码中。

    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
    

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 2014-08-27
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      相关资源
      最近更新 更多