Hoppa till huvudinnehåll

Hur går man igenom filer i en katalog och kopierar data till ett huvudark i Excel?

Antag att det finns flera Excel-arbetsböcker i en mapp, och du vill slinga igenom alla dessa Excel-filer och kopiera data från angivet intervall med samma namn-kalkylblad till ett huvudark i Excel, vad kan du göra? Denna artikel introducerar en metod för att uppnå det i detalj.

Sök igenom filer i en katalog och kopiera data till ett huvudark med VBA-kod


Sök igenom filer i en katalog och kopiera data till ett huvudark med VBA-kod

Om du vill kopiera specificerad data i intervall A1: D4 från alla ark1 av arbetsböcker i en viss mapp till ett huvudark, gör så här.

1. I arbetsboken skapar du ett huvudark, tryck på andra + F11 nycklar för att öppna Microsoft Visual Basic för applikationer fönster.

2. I Microsoft Visual Basic för applikationer fönstret klickar Insert > Modulerna. Kopiera sedan VBA-koden nedan till kodfönstret.

VBA-kod: slinga igenom filer i en mapp och kopiera data till ett huvudark

Sub Merge2MultiSheets()
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook, xWorkBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    xSheetName = "Sheet1"
    xRgStr = "A1:D4"
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            Set xWorkBook = ThisWorkbook
            Set xSheet = xWorkBook.Sheets("New Sheet")
            If xSheet Is Nothing Then
                xWorkBook.Sheets.Add(after:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "New Sheet"
                Set xSheet = xWorkBook.Sheets("New Sheet")
            End If
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            Do Until xFileName = ""
               Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
                Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
                xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Anmärkningar:

1). I koden, “A1: D4"Och"Sheet1”Betyder att data i intervall A1: D4 för hela ark 1 kommer att kopieras till huvudarket. Och “Nytt blad”Är namnet på det nya skapade huvudarket.
2). Excel-filerna i den specifika mappen ska inte öppnas.

3. tryck på F5 för att köra koden.

4. I öppningen Bläddra välj mappen som innehåller filerna du kommer att gå igenom och klicka sedan på OK knapp. Se skärmdump:

Sedan skapas ett huvudkalkylblad med namnet "Nytt ark" i slutet av den nuvarande arbetsboken. Och data i intervall A1: D4 för alla ark 1 i vald mapp listas inuti kalkylbladet.


Relaterade artiklar:

Bästa kontorsproduktivitetsverktyg

🤖 Kutools AI Aide: Revolutionera dataanalys baserat på: Intelligent utförande   |  Generera kod  |  Skapa anpassade formler  |  Analysera data och generera diagram  |  Anropa Kutools funktioner.
Populära funktioner: Hitta, markera eller identifiera dubbletter   |  Ta bort tomma rader   |  Kombinera kolumner eller celler utan att förlora data   |   Rund utan formel ...
Superuppslag: Flera kriterier VLookup    VLookup med flera värden  |   VSök över flera ark   |   Fuzzy Lookup ....
Avancerad rullgardinslista: Skapa snabbt en rullgardinslista   |  Beroende rullgardinslista   |  Flervals-rullgardinslista ....
Kolumnhanterare: Lägg till ett specifikt antal kolumner  |  Flytta kolumner  |  Växla synlighetsstatus för dolda kolumner  |  Jämför intervall och kolumner ...
Utvalda funktioner: Rutnätsfokus   |  Designvy   |   Stor formelbar    Arbetsbok & Bladhanterare   |  Resursbibliotek (Automatisk text)   |  Datumväljare   |  Kombinera arbetsblad   |  Kryptera/Dekryptera celler    Skicka e-postmeddelanden efter lista   |  Superfilter   |   Specialfilter (filtrera fet/kursiv/genomstruken...) ...
Topp 15 verktygssatser12 text verktyg (lägga till text, Ta bort tecken, ...)   |   50+ Diagram Typer (Gantt Chart, ...)   |   40+ Praktiskt Formler (Beräkna ålder baserat på födelsedag, ...)   |   19 Införande verktyg (Infoga QR-kod, Infoga bild från sökväg, ...)   |   12 Konvertering verktyg (Siffror till ord, Valutaväxling, ...)   |   7 Slå ihop och dela verktyg (Avancerade kombinera rader, Dela celler, ...)   |   ... och mer

Uppgradera dina Excel-färdigheter med Kutools för Excel och upplev effektivitet som aldrig förr. Kutools för Excel erbjuder över 300 avancerade funktioner för att öka produktiviteten och spara tid.  Klicka här för att få den funktion du behöver mest...

Beskrivning


Fliken Office ger ett flikgränssnitt till Office och gör ditt arbete mycket enklare

  • Aktivera flikredigering och läsning i Word, Excel, PowerPoint, Publisher, Access, Visio och Project.
  • Öppna och skapa flera dokument i nya flikar i samma fönster, snarare än i nya fönster.
  • Ökar din produktivitet med 50 % och minskar hundratals musklick för dig varje dag!
Comments (22)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Good afternoon. I urgently need your help: what VBA code could I use to copy a folder from an Excel workbook and paste it into an existing Excel workbook in another workbook? Would it be possible to copy the formatting just from the formatting?
This comment was minimized by the moderator on the site
Boa tarde. Preciso urgentemente de sua ajuda: qual código de VBA poderia utilizar para copiar a uma planilha inteira de uma pasta de trabalho Excel e colar em várias outras pastas de trabalho Excel já existentes em uma em um mesmo diretório? Teria como copiar apenas a formatação da planilha inteira?
This comment was minimized by the moderator on the site
My scenario is similar, except I have multiple sheets in each file, all with different names but consistent between files. Is there a way to Loop this code to copy the data within the files and paste (values) to specific sheet names in the master workbook? The sheet names in the master are the same as in the files. I want to loop through them. Also, the amount of data in each sheet will vary, so I will need to select the data in each sheet using something like this:

Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select


File sheet names are Giving, Services, Insurance, Car, Other Expenses, etc...

Thanks in advance.
This comment was minimized by the moderator on the site
Hi Andrew Shahan,
The following VBA code can solve your problem. After running the code and selecting a folder, the code will automatically match the worksheet by name and paste the data into the worksheet of the same name in the master workbook.
Sub Merge2MultiSheets()
'Updated by Extendoffice 20221209
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook As Workbook, xMainBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Set xMainBook = ThisWorkbook
    
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            
            Do Until xFileName = ""
            Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)

            For Start = 1 To xBook.Worksheets.Count
                Set xSheet = xBook.Worksheets.Item(Start)
                xSheet.Activate
                xSheetName = xSheet.Name
                xSheet.UsedRange.Copy (xMainBook.Worksheets.Item(xSheetName).Range("A1048576").End(xlUp).Offset(1, 0))
            Next
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Olá bom dia.
Gostei muito dessde código, mas não me ajudou com os relatórios que eu preciso impreimir.
Preciso imprimir 2.400 relatório de exel que estão em pastas diferentes e não estão configuradas corretamente para impressão. Pode me enviar um códgo de VBA que automatize essas impressões ? Me ajudaria muito, obrigada.
This comment was minimized by the moderator on the site
Hi Maria Soares,
Please check if the VBA code in the following post can help.
How to print multiple workbooks in Excel?
This comment was minimized by the moderator on the site
Hi i want a code to copy the data in 6 different workbooks(in a folder) which has sheets included in them to NEW WORKBOOK. in vba
plz help me asp
This comment was minimized by the moderator on the site
Hi Paranusha,
The VBA script in the following article can combine multiple workbooks or specified sheets of workbooks to a master workbook. Please check if it can help.
How To Combine Multiple Workbooks Into One Master Workbook In Excel?
This comment was minimized by the moderator on the site
for me, the "Sheet1" tab name changes for each of my files. For instance, Tab1, Tab2, Tab3, Tab4...How can I setup a loop to run through a list in excel and keep changing the "Sheet1" name until it runs through everything?
This comment was minimized by the moderator on the site
Hi Nick,The VBA code below can help you solve the problem. Please have a try.<div data-tag="code">Sub LoopThroughFileRename()
'Updated by Extendofice 2021/12/31
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
Dim xShs As Sheets
Dim xName As String
Dim xFNum As Integer
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
xFileDlg.Show
xSelItem = xFileDlg.SelectedItems.Item(1)
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
Do While xFileName <> ""
Set xWorkBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xShs = xWorkBook.Sheets
For xFNum = 1 To xShs.Count
Set xSheet = xShs.Item(xFNum)
xName = xSheet.Name
xName = Replace(xName, "Sheet", "Tab") 'Replace Sheet with Tab
xSheet.Name = xName
Next
xWorkBook.Save
xWorkBook.Close
xFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
how do you make to code leave a blank if cell is empty?
This comment was minimized by the moderator on the site
Thank you - how would one be able to copy and paste (special values) from each worksheet within a workbook into separate sheets within a main Master file?
This comment was minimized by the moderator on the site
Hi - This code works very well for the first 565 lines for every file, but all lines after are overlapped by the next file.
is there a way to fix this?
This comment was minimized by the moderator on the site
Hi - This code is perfect for what I'm trying to achieve.

Is there a way to loop through all folders and subfolders and perform the copy?


Thanks!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations