首页 > 解决方案 > 根据条件复制数据

问题描述

我有一张包含一些数据的表格和另一张只有列标题的空白表格。我想根据区域应该是“非洲”的标准将数据从初始工作表复制到另一张工作表中。

我使用下面的代码复制数据,但它多次复制初始工作表中的第一行,而不是区域为“非洲”的所有数据行。这是我的代码片段:

'Assigning the arrays to variables to return column index number
    ws1Headers = getIndexes(ws1.Rows(4), mHeaders)
    ws2Headers = getIndexes(ws2.Rows(2), soHeaders)
    
    'Setting first and last row for the columns in both sheets
    ws1SORow = 5              'The row we want to start processing first
    ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.count).Row
    ws2SORow = 3              'The row we want to start search first
    ws2EndRow = ws2.UsedRange.Rows(ws2.UsedRange.Rows.count).Row

   'iterate through search terms
    For i = ws1SORow To ws1EndRow     'first and last row
        searchKey = ws1.Range("A" & i)

        If (searchKey = "") Then
            For j = ws2SORow To ws2EndRow    'first and last row
                foundKey = ws2.Range("O" & j)
                  'Copy result if there is a match
                 If (foundKey = "Africa") Then
                    'Copying data where the headers match
                    For k = LBound(ws2Headers) To UBound(ws2Headers)
                        ws1.Cells(i, ws1Headers(k)) = ws2.Cells(j, ws2Headers(k))
                    Next k
                    Exit For
                 End If
            Next
        End If
    Next

我有一个函数可以获取标题的索引,并且还定义了标题名称,我没有包括在内,因为它有很多代码。非常感谢对发布的查询提供任何帮助。

标签: excelvbacopy

解决方案


推荐阅读