将文件夹下所有csv文件里内容拷贝到新的excle文件中

Sub LoopThroughFiles()
Dim MyFile As String, MyPath As String, MyExtension As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim NewBook As Workbook
    Dim NewSheet As Worksheet
    Dim SheetName As String
    
 
'Prompt the user to select the folder containing the CSV files
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select the folder containing the CSV files"
        .Show
        If .SelectedItems.Count = 0 Then
            MsgBox "No folder selected. The macro will now exit.", vbCritical, "Error"
            Exit Sub
        End If
        MyPath = .SelectedItems(1) & "\"
    End With
    
    'Set the file extension to CSV
    MyExtension = "*.csv"
    
    'Get the first CSV file in the folder
    MyFile = Dir(MyPath & MyExtension)
    
    'Create a new Excel workbook
Application.DisplayAlerts = False
Set NewBook = Workbooks.Add
    
    'Loop through all CSV files in the folder
    Do While MyFile <> ""
        
        'Open the CSV file
        Set wb = Workbooks.Open(MyPath & MyFile)
        
        'Loop through all sheets in the CSV file
        For Each ws In wb.Worksheets
            
            'Copy the sheet to the new workbook
            ws.Copy After:=NewBook.Sheets(NewBook.Sheets.Count)
            
            'Get the name of the copied sheet
            SheetName = ws.Name
            
            'Rename the copied sheet to match the original sheet name
            Set NewSheet = NewBook.Sheets(NewBook.Sheets.Count)
            NewSheet.Name = SheetName
            
        Next ws
        
        'Close the CSV file
        wb.Close SaveChanges:=False
        
        'Get the next CSV file in the folder
        MyFile = Dir()
        
    Loop
 NewBook.Sheets("Sheet1").Delete
'Prompt the user to select the folder and filename for the new workbook
    With Application.FileDialog(msoFileDialogSaveAs)
        .Title = "Save the new workbook"
        .InitialFileName = "NewWorkbook.xlsx"
        .Show
        If .SelectedItems.Count = 0 Then
            MsgBox "No file selected. The macro will now exit.", vbCritical, "Error"
            Exit Sub
        End If
        NewBook.SaveAs Filename:=.SelectedItems(1), FileFormat:=xlOpenXMLWorkbook
    End With
    NewBook.SaveAs Filename:="F:\Rum\NewWorkbook.xlsx", FileFormat:=xlOpenXMLWorkbook
    
    'Close the new workbook
NewBook.Close SaveChanges:=True
Application.DisplayAlerts = True
    
End Sub



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值