Excel VBA - копирование с нескольких листов с условием и размещение в определенной ячейке на разных листах - PullRequest
0 голосов
/ 04 января 2019

Я новичок в VBA Excel, и у меня есть некоторый код, который будет проходить через несколько листов и копировать значения в определенном диапазоне ячеек, если критерии удовлетворены.

Так что в основном я хотел бы скопировать определенные данныеиз нескольких листов и вставьте его в определенные ячейки (он должен быть размещен на основе переменной в ячейках)

Я хотел бы скопировать из листа 1, 2, 3 и т. д. ячейку E в L и поместитьэто на другом листе, на основе значения ячейки L5:
I would like to copy from sheet 1, 2, 3, etc., cell E to L and place it in another sheet, based on the value of cell L5

И вставьте его на этот лист, в ячейку F в M, если значение ячейки Cв шаблоне листа 1 то же самое с ячейкой L5 в листе 1,2,3 и т. д .:
And paste it to this sheet, in cell F to M, if the value of cell C in sheet Template 1 are the same with cell L5 in sheet 1,2,3,etc.

Вот код, который у меня есть:

 Option Explicit

'Note: This example use the function LastRow
'This example copy the range A2:G2 from each worksheet.
'
'Change the range here
'
''Fill in the range that you want to copy
'Set CopyRng = sh.Range("A2:G2")

'When you run one of the examples it will first delete the summary worksheet
'named RDBMergeSheet if it exists and then adds a new one to the workbook.
'This ensures that the data is always up to date after you run the code.

'*****READ THE TIPS on the website****

Sub CopyRangeFromMultiWorksheets()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim CopyRng As Range
    Dim i As Integer

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    'Application.DisplayAlerts = False
    'On Error Resume Next
    'ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    'On Error GoTo 0
    'Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets("Template 1")
    'DestSh.Name = "RDBMergeSheet"

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets

        'Loop through all worksheets except the RDBMerge worksheet and the
        'Information worksheet, you can ad more sheets to the array if you want.
        If IsError(Application.Match(sh.Name, _
                                     Array("Information", "Template 1", "Template 2", "Template 3"), 0)) Then


            'Find the last row with data on the DestSh
            Last = LastRow(DestSh)

            'Fill in the range that you want to copy
            Set CopyRng = sh.Range("E10:L10")

            'Test if there enough rows in the DestSh to copy all the data
            If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                MsgBox "There are not enough rows in the Destsh"
                GoTo ExitTheSub
            End If


            'This example copies values/formats, if you only want to copy the
            'values or want to copy everything look at the example below this macro
            'For i = 2 To LastRow(DestSh)
            CopyRng.Copy
            With DestSh.Cells(Last + 1, "E")
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
            End With

            'Optional: This will copy the sheet name in the H column
            'DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name

        End If
    Next

ExitTheSub:

    Application.GoTo DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

Приведенный выше код удалось скопировать из листа 1, 2, 3 и т. Д. В диапазоне ячеек, но поместить его в последнюю строку, но пока не на основе критериев.Я хотел бы знать, как включить критерии, которые мне нужны, в код выше?Спасибо

1 Ответ

0 голосов
/ 07 августа 2019

Этот код подходит для циклов, которые находят лист, где значение L5 соответствует значению C1 в каждом из шаблонов.Внутри этого оператора if вы можете поместить имеющийся у вас код, который копирует и вставляет значения.Удачи!

 Sub matchTemplateWithSheet()
 '
 ' matchTemplateWithSheet Macro
 '

 '
 Dim x As Integer
 Dim y As Integer
 Dim a As Integer
 Dim b As Integer
 Dim numberOfTemplates As Integer
 Dim numberOfSheets As Integer

 numberOfTemplates = 3  'you can set the number of templates you're trying to fill
 numberOfSheets = 5      ' you can set the number of sheets you're looking through. _
                        this can also easily be automated in the code

 For x = 1 To numberOfTemplates
     a = ActiveWorkbook.Worksheets("Template " & x).Cells(1, 3)

     For y = 1 To numberOfSheets
         b = ActiveWorkbook.Worksheets("Sheet" & y).Cells(5, 12)

         If a = b Then

             '''''This is where you can put the copy/paste code that you already have'''''

          End If

     Next y

Next x



 End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...