【问题标题】:Importing multiple CSV to multiple worksheet in a single workbook将多个 CSV 导入单个工作簿中的多个工作表
【发布时间】:2012-08-23 03:37:21
【问题描述】:

我该怎么做?基本上我希望我的多个 CSV 文件被导入到多个工作表中,但只在一个工作簿中。这是我要循环的 VBA 代码。我需要循环来查询C:\test\中的所有CSV

Sub Macro()
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\test\test1.csv", Destination:=Range("$A$1"))
    .Name = "test1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Sheets.Add After:=Sheets(Sheets.Count)
End Sub

【问题讨论】:

    标签: vba excel csv


    【解决方案1】:

    我没有尝试过,但我会选择this

    Dim NumFound As Long 
    With Application.FileSearch 
        .NewSearch
        .LookIn = "C:\test\"
        .FileName = "*.csv"
        If .Execute() > 0 Then 
            For i = 1 To .FoundFiles.Count
                With ActiveSheet.QueryTables.Add(Connection:= _
                    "TEXT;" & "C:\test\" & (Application.FileSearch.FoundFiles(i)), Destination:=Range("$A$1"))
                    ...
                End With
                Sheets.Add After:=Sheets(Sheets.Count)
            Next i
        End If
    End With
    

    【讨论】:

    • Application.FileSearch 在 Office 2007 中已弃用,因此不太适合
    【解决方案2】:

    请注意,这不会像导入 csv 时会出现重复的工作表名称那样处理错误。

    这使用早期绑定,因此您需要在VBE 中的Tools..References 下引用Microsoft.Scripting.Runtime

    Dim fs  As New FileSystemObject
    Dim fo As Folder
    Dim fi As File
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim sname As String
    
    Sub loadall()
        Set wb = ThisWorkbook
    
        Set fo = fs.GetFolder("C:\TEMP\")
    
        For Each fi In fo.Files
            If UCase(Right(fi.name, 4)) = ".CSV" Then
                sname = Replace(Replace(fi.name, ":", "_"), "\", "-")
    
                Set ws = wb.Sheets.Add
                ws.name = sname
                Call yourRecordedLoaderModified(fi.Path, ws)
            End If
        Next
    End Sub
    
    Sub yourRecordedLoaderModified(what As String, where As Worksheet)
    With ws.QueryTables.Add(Connection:= _
        "TEXT;" & what, Destination:=Range("$A$1"))
        .name = "test1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Sheets.Add After:=Sheets(Sheets.Count)
    End Sub
    

    【讨论】:

      【解决方案3】:

      您可以使用Dir 过滤掉并仅使用csv 文件运行

      Sub MacroLoop()
      Dim strFile As String
      Dim ws As Worksheet
      strFile = Dir("c:\test\*.csv")
      Do While strFile <> vbNullString
      Set ws = Sheets.Add
      With ws.QueryTables.Add(Connection:= _
          "TEXT;" & "C:\test\" & strFile, Destination:=Range("$A$1"))
          .Name = strFile
          .FieldNames = True
          .RowNumbers = False
          .FillAdjacentFormulas = False
          .PreserveFormatting = True
          .RefreshOnFileOpen = False
          .RefreshStyle = xlInsertDeleteCells
          .SavePassword = False
          .SaveData = True
          .AdjustColumnWidth = True
          .RefreshPeriod = 0
          .TextFilePromptOnRefresh = False
          .TextFilePlatform = 437
          .TextFileStartRow = 1
          .TextFileParseType = xlDelimited
          .TextFileTextQualifier = xlTextQualifierDoubleQuote
          .TextFileConsecutiveDelimiter = False
          .TextFileTabDelimiter = False
          .TextFileSemicolonDelimiter = False
          .TextFileCommaDelimiter = True
          .TextFileSpaceDelimiter = False
          .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
          .TextFileTrailingMinusNumbers = True
          .Refresh BackgroundQuery:=False
      End With
      strFile = Dir
      Loop
      End Sub
      

      【讨论】:

      • 工作表名称不反映此代码的 CSV 文件的文件名。我该如何解决?
      • 我已经解析了工作表的文件名。我的新问题是,我的内存不足错误。我正在导入大约 80 个 CSV 文件。
      • @Dumont 关于文件名,我想你看到我使用了一个变量。在您的记忆错误中,它导入了多少个 CSV?您接受的其他代码是否使用相同的导入方法(但首先测试每种文件类型)
      • 是的,它给出了同样的错误。我正在导入大约 80 个 CSV 文件。
      • 现在好了。当 CSV 没有内容时,代码似乎失败了。我刚刚添加了On Error Resume Next
      【解决方案4】:

      This guy 绝对做到了。非常简洁的代码,在 2010 年非常适合我。所有功劳都归功于他(Jerry Beaucaire)。我是从论坛here找到的。

      Option Explicit
      Sub ImportCSVs()
      'Author:    Jerry Beaucaire
      'Date:      8/16/2010
      'Summary:   Import all CSV files from a folder into separate sheets
      '           named for the CSV filenames
      
      'Update:    2/8/2013   Macro replaces existing sheets if they already exist in master workbook
      
      Dim fPath   As String
      Dim fCSV    As String
      Dim wbCSV   As Workbook
      Dim wbMST   As Workbook
      
      Set wbMST = ThisWorkbook
      fPath = "C:\test\"                  'path to CSV files, include the final \
      Application.ScreenUpdating = False  'speed up macro
      Application.DisplayAlerts = False   'no error messages, take default answers
      fCSV = Dir(fPath & "*.csv")         'start the CSV file listing
      
          On Error Resume Next
          Do While Len(fCSV) > 0
              Set wbCSV = Workbooks.Open(fPath & fCSV)                    'open a CSV file
              wbMST.Sheets(ActiveSheet.Name).Delete                       'delete sheet if it exists
              ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count)    'move new sheet into Mstr
              Columns.Autofit             'clean up display 
              fCSV = Dir                  'ready next CSV
          Loop
      
      Application.ScreenUpdating = True
      Set wbCSV = Nothing
      End Sub
      

      【讨论】:

      • 这似乎不适用于 2013 年(除非我遗漏了什么。)我将此脚本复制到启用宏的 Excel 工作簿(2013 年)并运行它(其中包含两个 .csv 文件指定的目录)。当我运行它时,它打开了两个新的 Excel 实例(两个新工作簿),每个实例都有一个工作表,而我的原始工作簿中没有任何内容。脚本需要更新吗?
      • 我可能没有时间调查,抱歉。欢迎提供更新的答案。
      【解决方案5】:

      我有 183 个 csv 文件要压缩到一个工作簿中,每个 csv 文件一个工作表以方便分析数据,并且不想一次手动执行此操作。我在这个问题上尝试了最高评价的解决方案,但与另一个用户有同样的问题; csv 文件将打开,但不会将任何内容插入到目标工作簿中。我花了一些时间调整了代码,使其在 Excel 2016 中运行。我没有在旧版本上进行测试。我已经很久没有用 Visual Basic 编码了,所以我的代码可能还有很大的改进空间,但它在紧要关头对我有用。如果有人碰巧像我一样偶然发现这个问题,我将粘贴我在下面使用的代码。

      Option Explicit
      Sub ImportCSVs()
      'Author:    Jerry Beaucaire
      'Date:      8/16/2010
      'Summary:   Import all CSV files from a folder into separate sheets
      '           named for the CSV filenames
      
      'Update:    2/8/2013   Macro replaces existing sheets if they already exist in master workbook
      'Update: base script as seen in: https://sites.google.com/a/madrocketscientist.com/jerrybeaucaires-excelassistant/merge-functions/csvs-to-sheets
      'Update: adjusted code to work in Excel 2016
      
      Dim fPath   As String
      Dim fCSV    As String
      Dim wbName  As String
      Dim wbCSV   As Workbook
      Dim wbMST   As Workbook
      
      
      wbName = "this is a string"
      Set wbMST = ThisWorkbook
      
      fPath = "C:\pathOfCSVFiles\"                  'path to CSV files, include the final \
      Application.ScreenUpdating = False  'speed up macro
      Application.DisplayAlerts = False   'no error messages, take default answers
      fCSV = Dir(fPath & "*.csv")         'start the CSV file listing
      
          On Error Resume Next
          Do While Len(fCSV) > 0
              Set wbCSV = Workbooks.Open(fPath & fCSV)                    'open a CSV file
              If wbName = "this is a string" Then 'this is to check if we are just starting out and target workbook only has default Sheet 1
                  wbCSV.Sheets.Copy After:=wbMST.Sheets(1) 'for first pass, can leave as is. if loading a large number of csv files and excel crashes midway, update this to the last csv that was loaded to the target workbook
              Else
                  wbCSV.Sheets.Copy After:=wbMST.Sheets(wbName) 'if not first pass, then insert csv after last one
              End If
      
              fCSV = Dir                  'ready next CSV
              wbName = ActiveSheet.Name 'save name of csv loaded in this pass, to be used in the next pass
          Loop
      
      Application.ScreenUpdating = True
      Set wbCSV = Nothing
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2019-10-27
        • 1970-01-01
        • 2011-06-04
        • 2022-12-24
        • 1970-01-01
        • 2014-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多