Используя VBA (вместо чего-то вроде Power Query) и предполагая, что вы хотите скопировать данные с первого листа (открытой книги) и вставить в "Sheet1"
в Thisworkbook
, код может выглядеть примерно так:ниже.
Может быть хорошо сделать копию всей папки (содержащей .xlsx
файлов) перед запуском приведенного ниже кода (ненужного, но на всякий случай).
Если у вас есть сотнифайлов, которые нужно открыть, вы можете переключить Application.ScreenUpdating
до и после цикла For
(чтобы предотвратить ненужное мерцание и перерисовку экрана).
Option Explicit
Private Sub CopyPasteSheets()
Dim folderPath As String
folderPath = "C:\Users\WCS\Desktop\files\coworking\"
If Len(VBA.FileSystem.Dir$(folderPath, vbDirectory)) = 0 Then
MsgBox ("'" & folderPath & "' does not appear to be a valid directory." & vbNewLine & vbNewLine & "Code will stop running now.")
Exit Sub
End If
Dim filePathsFound As Collection
Set filePathsFound = New Collection
Dim Filename As String
Filename = VBA.FileSystem.Dir$(folderPath & "*.xlsx", vbNormal)
Do Until Len(Filename) = 0
filePathsFound.Add folderPath & Filename, Filename
Filename = VBA.FileSystem.Dir$()
Loop
Dim filePath As Variant ' Used to iterate over collection
Dim sourceBook As Workbook
Dim destinationSheet As Worksheet
Set destinationSheet = ThisWorkbook.Worksheets("Sheet1") ' Change to whatever yours is called
'destinationSheet.Cells.Clear ' Uncomment this line if you want to clear before beginning
Dim rowToPasteTo As Long
rowToPasteTo = destinationSheet.Cells(destinationSheet.Rows.Count, "A").End(xlUp).Row
If rowToPasteTo > 1 Then rowToPasteTo = rowToPasteTo + 1
For Each filePath In filePathsFound
On Error Resume Next
Set sourceBook = Application.Workbooks.Open(Filename:=filePath, ReadOnly:=True)
On Error GoTo 0
If Not (sourceBook Is Nothing) Then
With sourceBook.Worksheets(1) ' Might be better if you refer to sheet by name rather than index
Dim lastRowToCopy As Long
lastRowToCopy = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("A1:A" & lastRowToCopy).EntireRow
If (rowToPasteTo + .Rows.Count - 1) > destinationSheet.Rows.Count Then
MsgBox ("Did not paste rows from '" & sourceBook.FullName & "' due to lack of rows on sheet." & vbNewLine & vbNewLine & "Code will close that particular workbook and then stop running.")
sourceBook.Close
Exit Sub
End If
.Copy destinationSheet.Cells(rowToPasteTo, "A").Resize(.Rows.Count, 1).EntireRow
rowToPasteTo = rowToPasteTo + .Rows.Count
End With
End With
sourceBook.Close
Set sourceBook = Nothing
Else
MsgBox ("Could not open file at '" & CStr(sourceBook) & "'. Will try to open remaining workbooks.")
End If
Next filePath
End Sub