简体   繁体   English

Excel VBA复制表/行

[英]Excel VBA Copy Sheet/Line

I have 2 Master Sheets based on 2 conditions of location. 我有2个基于2个位置条件的母版表。 I import this data from an Excel Workbook into a worksheet on the Master Sheet Workbook. 我将这些数据从Excel工作簿导入到“主表工作簿”上的工作表中。 I think it would be better if I was able to scan the first column (A for example) and if the row meets a certain condition it would move the entire row to the respective Master Sheet just below the current data. 我认为如果能够扫描第一列(例如A)会更好,并且如果该行满足特定条件,它将把整行移到当前数据正下方的相应主表中。 If it meets condition B it goes to the other master sheet. 如果满足条件B,则转到另一张母版纸。 I can then use Remove Duplicates in Excel to filter the data. 然后,我可以在Excel中使用“删除重复项”来过滤数据。 My current code is below and I am fairly new to VB Automation. 我当前的代码在下面,我对VB Automation还是相当陌生。 Any ideas on what kind of code I could use to select and move the rows based on criteria into 2 seperate master worksheets? 关于可以用来根据标准选择行并将其移动到2个单独的主工作表中的哪种代码,有什么想法吗?

Sub Copy_DataCDN()
Sheets("CDNDataDump").Range("A2:AC10000").Copy _
Sheets("CDN").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
Sheets("CDN").Select

As you suggested, this can be done by looping through the cells in your condition column (in the example code it's column A). 如您所建议的,这可以通过循环查看条件列中的单元格来完成(在示例代码中,该列为A列)。

Here's the example code for you to modify. 这是供您修改的示例代码。

Sub MoveToSheets()
    Dim dataSource As Worksheet: Set dataSource = ThisWorkbook.Sheets(1)
    Dim dataTargetA As Worksheet: Set dataTargetA = ThisWorkbook.Sheets(2)
    Dim dataTargetB As Worksheet: Set dataTargetB = ThisWorkbook.Sheets(3)
    Dim dataSourceRange As Range: Set dataSourceRange = dataSource _
    .Range("A1:A" & dataSource.Cells(dataSource.Rows.Count, "A").End(xlUp).Row)

    For Each Cell In dataSourceRange
        'Test 1 - I'm checking if the cell value is a number as an example.
        If IsNumeric(Cell.Value) = True Then
            dataTargetA.Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.Value _
            = Cell.EntireRow.Value
        'Test 2 - Checking if the cell value is "e".
        ElseIf Cell.Value = "e" Then
            dataTargetB.Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.Value _
            = Cell.EntireRow.Value
        End If
    Next
End Sub

In the For Each Cell In dataSourceRange loop you can have as many conditions as you need. 在“数据源范围内的For Each Cell In dataSourceRange循环中,可以根据需要设置任意多个条件。 You could have more sheets to paste to as well. 您可能还需要粘贴更多的工作表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM