根据条件和在最后一列中复制数据的“标签”复制数据行

时间:2019-07-02 16:59:28

标签: excel vba

我有工作代码检查每一行中的条件,如果满足,则将整行数据复制到另一个工作簿中。但!我需要能够在复制的数据的最后一列(S列)中添加文本,该文本实际上标记了满足条件的条件,从而使代码对其进行了复制,因为我很快就会扩展到检查多个不同的条件。

因此,对于符合条件并被复制的每一行,我想在新工作簿的S列旁边添加“ Criteria1”(它将始终是S列,它将是第一个可用列)。

我已经通过继承和您的所有帮助将这段代码整理在一起,所以我什至不知道从哪里开始。

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

Dim CoderBook As Workbook
Dim Referrals As Worksheet
Dim Review As Workbook
Dim Crit As Worksheet
Dim LastRow As Long
Dim NextRow As Long
Dim i As Long

Set CoderBook = Workbooks.Open("Coder Referrals.xlsx")
Set Referrals = CoderBook.Sheets("Sheet1")

Set Review = ThisWorkbook
Set Crit = Review.Sheets("Criteria")


'Search code
LastRow = Crit.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Application.ScreenUpdating = False

'Loop search code
For i = 2 To LastRow

    'Specialized Criteria1 Check
    If Crit.Range("F" & i) <> Crit.Range("G" & i) Or _
    Crit.Range("I" & i) <> Crit.Range("J" & i) Then

            'If meets Criteria1 check, then copy appropriate rows to CoderBook Referrals sheet
            Referrals.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).EntireRow.Value = Crit.Rows(i).Value

    End If

Next i
'End loop code

CoderBook.Close SaveChanges:=True
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

将或分为两个语句:

For i = 2 To LastRow
    j = Referrals.Cells(Rows.Count, 1).End(xlUp).row + 1

    'Specialized Criteria1 Check
    If Crit.Range("F" & i) <> Crit.Range("G" & i) Then
        'If meets Criteria1 check, then copy appropriate rows to CoderBook Referrals sheet
        Referrals.Rows(j).EntireRow.Value = Crit.Rows(i).Value
        Referrals.Range("S" & j).Value = "Criteria1"
    End If
    If Crit.Range("I" & i) <> Crit.Range("J" & i) Then
        Referrals.Rows(j).EntireRow.Value = Crit.Rows(i).Value
        if Referrals.Range("S" & j).value = vbNullString then
            Referrals.Range("S" & j).Value = "Criteria2"
        Else
            Referrals.Range("S" & j).Value = Referrals.Range("S" & j).Value & ", " & "Criteria2"
    End if    
Next i