Skip i'r prif gynnwys

Sut i ddolennu trwy ffeiliau mewn cyfeiriadur a chopïo data i mewn i brif ddalen yn Excel?

Gan dybio bod nifer o lyfrau gwaith Excel mewn ffolder, a'ch bod am ddolen trwy'r holl ffeiliau Excel hyn a chopïo data o ystod benodol o daflenni gwaith o'r un enw i mewn i brif daflen waith yn Excel, beth allwch chi ei wneud? Mae'r erthygl hon yn cyflwyno dull i'w gyflawni mewn manylion.

Dolen trwy ffeiliau mewn cyfeiriadur a chopïo data i mewn i brif ddalen gyda chod VBA


Dolen trwy ffeiliau mewn cyfeiriadur a chopïo data i mewn i brif ddalen gyda chod VBA

Os ydych chi am gopïo data penodol yn ystod A1: D4 o bob dalen1 o lyfrau gwaith mewn ffolder benodol i brif ddalen, gwnewch fel a ganlyn.

1. Yn y llyfr gwaith byddwch yn creu prif daflen waith, pwyswch y Alt + F11 allweddi i agor y Microsoft Visual Basic ar gyfer Ceisiadau ffenestr.

2. Yn y Microsoft Visual Basic ar gyfer Ceisiadau ffenestr, cliciwch Mewnosod > Modiwlau. Yna copïwch isod god VBA i mewn i'r ffenestr cod.

Cod VBA: dolennu trwy ffeiliau mewn ffolder a chopïo data i mewn i brif ddalen

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

Nodyn:

1). Yn y cod, “A1: D4"A"Sheet1”Yn golygu y bydd data yn ystod A1: D4 yr holl Daflen 1 yn cael ei gopïo i'r brif ddalen. Ac ““Taflen Newydd”Yw enw'r brif ddalen newydd ei chreu.
2). Ni ddylai'r ffeiliau Excel yn y ffolder benodol agor.

3. Gwasgwch y F5 allwedd i redeg y cod.

4. Yn yr agoriad Pori ffenestr, dewiswch y ffolder sy'n cynnwys y ffeiliau y byddwch chi'n dolennu drwyddynt, ac yna cliciwch ar y OK botwm. Gweler y screenshot:

Yna crëir prif daflen waith o'r enw “New Sheet” ar ddiwedd y llyfr gwaith cyfredol. Ac mae data yn ystod A1: D4 o'r holl Daflen 1 mewn ffolder a ddewiswyd wedi'i restru y tu mewn i'r daflen waith.


Erthyglau cysylltiedig:

Offer Cynhyrchiant Swyddfa Gorau

🤖 Kutools AI Aide: Chwyldro dadansoddi data yn seiliedig ar: Cyflawniad Deallus   |  Cynhyrchu Cod  |  Creu Fformiwlâu Personol  |  Dadansoddi Data a Chynhyrchu Siartiau  |  Invoke Swyddogaethau Kutools...
Nodweddion Poblogaidd: Darganfod, Amlygu neu Adnabod Dyblygiadau   |  Dileu Rhesi Gwag   |  Cyfuno Colofnau neu Gelloedd heb Colli Data   |   Rownd heb Fformiwla ...
Super-edrych: VLookup Meini Prawf Lluosog    VLookup Gwerth Lluosog  |   VLookup Ar Draws Taflenni Lluosog   |   Edrych Niwlog ....
Rhestr gwympo Uwch: Creu Rhestr Gollwng yn Gyflym   |  Rhestr Gollwng Dibynnol   |  Rhestr Gollwng Aml-ddewis ....
Rheolwr Colofn: Ychwanegu Nifer Penodol o Golofnau  |  Symud Colofnau  |  Toglo Statws Gwelededd Colofnau Cudd  |  Cymharwch Ystodau a Cholofnau ...
Nodweddion dan Sylw: Ffocws ar y Grid   |  Golwg Dylunio   |   Bar Fformiwla Mawr    Rheolwr Llyfr Gwaith a Thaflen   |  Llyfrgell Adnoddau (Testun Auto)   |  Dewiswr Dyddiad   |  Cyfuno Taflenni Gwaith   |  Amgryptio/Dadgryptio Celloedd    Anfon E-byst trwy Restr   |  Hidlo Super   |   Hidlo Arbennig (hidlo mewn print trwm/italig/strikethrough...) ...
15 Set Offer Gorau12 Testun offer (Ychwanegu Testun, Dileu Cymeriadau,...)   |   50 + Siart Mathau (Siart Gantt,...)   |   40+ Ymarferol Fformiwlâu (Cyfrifwch oedran yn seiliedig ar ben-blwydd,...)   |   19 mewnosod offer (Mewnosod Cod QR, Mewnosod Llun o'r Llwybr,...)   |   12 Trosi offer (Rhifau i Eiriau, Trosi arian cyfred,...)   |   7 Uno a Hollti offer (Rhesi Cyfuno Uwch, Celloedd Hollt,...)   |   ... a mwy

Supercharge Eich Sgiliau Excel gyda Kutools ar gyfer Excel, a Phrofiad Effeithlonrwydd Fel Erioed Erioed. Kutools ar gyfer Excel Yn Cynnig Dros 300 o Nodweddion Uwch i Hybu Cynhyrchiant ac Arbed Amser.  Cliciwch Yma i Gael Y Nodwedd Sydd Ei Angen Y Mwyaf...

Disgrifiad


Mae Office Tab yn dod â rhyngwyneb Tabbed i Office, ac yn Gwneud Eich Gwaith yn Haws o lawer

  • Galluogi golygu a darllen tabbed yn Word, Excel, PowerPoint, Cyhoeddwr, Mynediad, Visio a Phrosiect.
  • Agor a chreu dogfennau lluosog mewn tabiau newydd o'r un ffenestr, yn hytrach nag mewn ffenestri newydd.
  • Yn cynyddu eich cynhyrchiant 50%, ac yn lleihau cannoedd o gliciau llygoden i chi bob dydd!
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