如何让宏仅在遇到特定过滤器时运行

时间:2019-01-02 20:38:13

标签: excel vba

我有一个很大的宏,它正在从主工作簿中进行大量复制,并提供15份每日报告并粘贴到源工作簿中。宏很大,我只会粘贴相关部分。

源文件通过以下代码与主工作簿匹配(一切正常):

 Public OutShVar As Worksheet   
 Public RngConcat As Range   

 Set OutShVar = ThisWorkbook.Worksheets("SourceSheet")
 Set RngConcat = OutShVar.Range("A:A")  
 Dim loc As Range
 Dim WCell As Range


 Concat = ShVar.Range(tC & i).Value 
 Set loc = RngConcat.Find(Concat) '(not relevant to this question, it's just setting loc to column A in my source file)


  CRV = loc.Offset(0, 2).Value

  'No CRV ID ID
  If loc.Offset(0, 2).Value = "Not Available" Then
  loc.Offset(0, 80) = "Y"
 Else
  loc.Offset(0, 80) = "N"

   'Line items from the masterwork book
  Set WCell = WShRange.Range("FW:FW").Find(CRV, lookat:=xlWhole)
   'a bunch of copy pasting

   loc.Offset(0, 26) = WCell.Offset(0, -177) 'an example
  End if
 End Sub

但是问题就在这里,现在我在源文件中的CRV密钥是这样的 CL810681AG5421BPGB-

但是,在主工作簿中,就像这样

column A                 Column B
Obligation Active        CRV Key
NO                       CL810681AG5421BPGB- 
NO                       CL810681AG5421BPGB-
YES                      CL810681AG5421BPGB-

如您所见,我的代码只会与第一行匹配,但是我希望我的代码首先找到“是”,然后如果找不到,请转到“否”。有可能吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下逻辑:

Option Explicit

Sub Test_Date()

    Dim CRV_Key_Yes As String, CRV_Key_No As String
    Dim Lastrow As Long, i As Long, Line As Long
    Dim Appears As Boolean

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        CRV_Key_Yes = "YES" & "_" & "CL810681AG5421BPGB-"
        CRV_Key_No = "NO" & "_" & "CL810681AG5421BPGB-"

        Appears = False

        For i = 2 To Lastrow

            If .Range("A" & i).Value & "_" & .Range("B" & i).Value = CRV_Key_Yes Then
                Line = i
                Appears = False
                Exit For
            ElseIf .Range("A" & i).Value & "_" & .Range("B" & i).Value = CRV_Key_No And Appears = False Then
                Line = i
                Appears = True
            End If

        Next i

        MsgBox "CRV Key match on line " & Line & "."

    End With

End Sub