Код VBA | Откройте все файлы в папке, запустите форматирование кода VBA, затем объедините все в одну таблицу

У меня есть несколько файлов Excel в папке, которые мне нужно отформатировать, а затем полученные файлы объединить в одну основную таблицу.

1. У меня есть код для открытия всех файлов в указанной папке следующим образом:

Sub Open_Workbooks()

    Dim myPath As String
    Dim myFile As String
    Dim wb As Workbook
    
    ' Specify the folder path containing the Excel files
        myPath = "C:\Users\Kuda\Documents\TRIAL BALANCES"
    
    
    ' Check for trailing backslash in folder path
        If Right(myPath, 1) <> "\" Then myPath = myPath & "\"
    
    
    ' Find the first Excel file in the folder
    myFile = Dir(myPath & "*.xls*")
    
    
    ' Loop through all Excel files in the folder
    Do While myFile <> ""
        ' Open the workbook
        Set wb = Workbooks.Open(myPath & myFile)
        
        ' Move to the next file (this line is essential to avoid an endless loop)
        myFile = Dir
    Loop
End Sub

2. Код форматирования будет:

Call tb_cleanup()

3. Теперь мне нужен третий код, который применяет код №2 ко всем открытым электронным таблицам, а затем копирует отформатированные данные из каждой открытой электронной таблицы, а затем вставляет их, укладывая их один за другим в одну главную электронную таблицу.

#4 Четвертый код — это один код в единственном числе, который объединяет все три вышеперечисленных кода в одном.

Итак, могу ли я получить помощь с кодом для пунктов 3 и 4, как указано выше.

Код для tb-cleanup:

Sub tb_cleanup()

Dim A, B


If Range("D11").Value <> "Account" Then

    MsgBox "Not applicable here.", vbOKOnly, "FOR TB ONLY!!"
    Exit Sub
    
End If

Application.ScreenUpdating = False

    
    A = Range("A2").Value
    B = Range("B2").Value
    
    
    Cells.Select
    Selection.UnMerge
    Columns("C:C").Select
    Selection.Delete Shift:=xlToLeft
    
    
    Rows("1:10").Select
    Range("A10").Activate
    Selection.Delete Shift:=xlUp
    
    Range("G1").Value = "Business Unit"
    Range("H1").Value = "Month"
    Range("I1").Value = "Year"
    
Dim xRow
xRow = Cells.Find(What: = "*", After:=Range("A1"), LookIn:=xlFormulas2, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False _
        , SearchFormat:=False).Row
         
         
Dim k

k = xRow - 5

    ' delete last unnec rows
    Rows(k & ":" & xRow).Select
    Selection.Delete Shift:=xlUp
    
    

xRow = Cells.Find(What: = "*", After:=Range("A1"), LookIn:=xlFormulas2, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False _
        , SearchFormat:=False).Row
         
         
    'put BU + Date

    Range("G2:G" & xRow).FormulaR1C1 = A
    
    Range("H2:H" & xRow).FormulaR1C1 = Format(B, "MMM")
    Range("I2:I" & xRow).FormulaR1C1 = Format(B, "yyyy")
    
    
    Range("G2").Select
    
    Range("B2").Select
    Range(Selection, Selection.End(xlToRight)).Select
    ActiveWindow.FreezePanes = True
    
    Range("A1:I" & xRow).Select
    Selection.Columns.AutoFit
   
    Range("G2").Select
    
    Call myTable
    
xRow = Cells.Find(What: = "*", After:=Range("A1"), LookIn:=xlFormulas2, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False _
        , SearchFormat:=False).Row
         

    Range("B2:B" & xRow).Select
    With Selection
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
        Selection.InsertIndent 1
        
        
        ActiveWindow.Zoom = 75
    Range("A1:I" & xRow).Select
    Selection.RowHeight = 18
    
    With Selection
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = -1
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    
    With Selection.Font
        .Name = "Aptos Display"
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMajor
    End With
    
    With Selection.Font
        .Name = "Aptos Display"
        .Size = 11
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMajor
    End With
    
    Range("D2:F" & xRow).Select
    Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
    
    Range("A1:I" & xRow).Select
    Selection.Columns.AutoFit
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
       
    
    
    Range("A1").Select
    Application.ScreenUpdating = True

 
End Sub

вызов myTable выглядит следующим образом:

Sub myTable()

    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Font.Bold = True
    With Selection.Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent4
        .TintAndShade = 0.599993896298105
        .PatternTintAndShade = 0
    End With

    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    
    Cells.EntireColumn.AutoFit

    Range("A1").Select
    
    
    
End Sub

Тогда попробуйте и дайте нам знать, где вы застряли.

jsheeran 24.07.2024 17:29

Так в чем ваш вопрос?

Mark S. 24.07.2024 17:32

@Метки. - вопрос по пунктам 3 и 4. Мне нужны коды для них

Kuda Magaya 25.07.2024 11:23

Пожалуйста, поделитесь кодом tb_cleanup, чтобы его можно было соответствующим образом изменить (по крайней мере, добавить объект рабочего листа в качестве параметра): Sub tb_cleanup(ByVal ws As Worksheet). А как насчет мастер-листа?

VBasic2008 25.07.2024 13:02

@Метки. - Я обновил код в Вопросе. Это довольно долго. Если есть способ сократить его, попробуйте, пожалуйста. Что касается мастер-листа, это конечный пункт назначения всех данных, которые будут вставлены с одного листа на другой, вставлены и уложены друг за другом на мастер-листе.

Kuda Magaya 25.07.2024 13:32
Преобразование HTML-таблицы в профессиональный документ Excel
Преобразование HTML-таблицы в профессиональный документ Excel
Это самый простой способ создания Excel из HTML-таблицы.
Импорт excel в laravel в базу данных
Импорт excel в laravel в базу данных
Здравствуйте, дорогой читатель, в этой статье я расскажу практическим и быстрым способом, как импортировать файл Excel в вашу базу данных с помощью...
0
5
71
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вместо того, чтобы открывать все файлы одновременно и вносить изменения, они будут открываться по одному и проходить по всей папке до завершения.

1. Создайте мастер-файл в своей папке и назовите его «1. Консолидатор файлов». Убедитесь, что все файлы в папке, открываемой основным файлом, имеют формат .xlsb (или, если он отличается, измените тип расширения в макросе «AllFiles» ниже).

2. Откройте главный файл и переименуйте вкладку в «Консолидатор файлов».

3. Создайте макрос, в котором вы будете запускать:

Sub AllFiles()
  Dim folderPath As String
  Dim filename As String
  Dim wb As Workbook
  Dim wb2 As Workbook
  folderPath = ActiveWorkbook.Path

    If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
    filename = Dir(folderPath & "*.xlsb")
    Do While filename <> ""
    Application.ScreenUpdating = False
    Set wb2 = Workbooks.Open(folderPath & filename)

   'Call a subroutine here to operate on the just-opened workbook
    Call tb_cleanup

   'Call 2nd subroutine to copy and paste opened workbook into master file
    Call GenFileToCall

    filename = Dir
    Loop
  Application.ScreenUpdating = True
  MsgBox ("File Consolidator ran successfully")
End Sub

Создайте второй макрос «GenFileToCall» (вызванный выше), чтобы скопировать открытые книги в главный файл:

Sub GenFileToCall()
  Dim Lastrow As Long
  Set wb = Application.Workbooks("1. File Consolidator.xlsm")
  Set wb2 = Application.ActiveWorkbook

    If ActiveSheet.FilterMode Then wb2.Sheets("Sheet1").ShowAllData

   'Find last row in wb2
    With wb2.Sheets("Sheet1")
    Lastrow = .Range("A:AS").Find("*", , , , xlByRows, xlPrevious).Row
    End With

   'Copy range from A2:AS until last row then close
    wb2.Sheets("Sheet1").Range("A2:AS" & Lastrow).Copy
    Application.DisplayAlerts = False

   'Make wb1 active workbook again
    wb.Activate

   'Find last row in wb1
    With wb.Sheets("File Consolidator")
    Lastrow = .Range("A:AS").Find("*", , , , xlByRows, xlPrevious).Row
    End With

   'Paste in wb1 after last row
    wb.Sheets("File Consolidator").Range("A" & Lastrow + 1).PasteSpecial xlPasteValues
    wb.Sheets("File Consolidator").Range("A" & Lastrow + 1).PasteSpecial xlPasteFormats

   'Close wb2 (Test File)
    wb2.Close
End Sub

Переменная Lastrow в «GenFileToCall» не определена в моей книге. Не могли бы вы помочь с определением этого понятия?

Kuda Magaya 25.07.2024 11:20

@KudaMagaya Он заполнен свойством Range.Row, которое представляет собой Long тип данных. Итак, это будет Dim Lastrow As Long

Chronocidal 25.07.2024 13:40

@Chronocidal - сработало. Спасибо! cgwol — пожалуйста, обновите Dim, чтобы другие пользователи могли использовать его позже.

Kuda Magaya 25.07.2024 14:03

@KudaMagaya Конечно, рад, что помогло

cgwoz 25.07.2024 15:26

Другие вопросы по теме