【问题标题】:Loop in Columns and Rows to find and copy values在列和行中循环以查找和复制值
【发布时间】:2021-04-15 05:58:36
【问题描述】:

我需要为图片中的下表创建一个多循环。

循环需要找到并复制所有行(例如):
如果 Bat=1 且 Bet=1 且 Bit=F 且 Bot = 1 且 But=1,则将该行复制到另一个工作表。

它需要是动态的,因为数据每天都在变化,我需要为每个“分类”行创建一个循环,例如:1-1-F-1-1、1-1-J-1 -1 等等。

我在这里搜索了很多主题。

我试过了:

Option Explicit
    
Sub Test()
    
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("base")
    Dim ARow As Long, BRow As Long, CRow As Long, DRow As Long, ERow As Long, MyCellA As Range, MyCellB As Range, MyCellC As Range, MyCellD As Range, MyCellE As Range, Names As String
    ARow = ws.Range("A" & ws.Rows.count).End(xlUp).Row
    BRow = ws.Range("B" & ws.Rows.count).End(xlUp).Row
    CRow = ws.Range("C" & ws.Rows.count).End(xlUp).Row
    DRow = ws.Range("D" & ws.Rows.count).End(xlUp).Row
    ERow = ws.Range("E" & ws.Rows.count).End(xlUp).Row
    
    For Each MyCellA In ws.Range("A2:A" & ARow)
        For Each MyCellB In ws.Range("B2:B" & BRow)
            For Each MyCellC In ws.Range("C2:C" & CRow)
                For Each MyCellD In ws.Range("D2:D" & DRow)
                    For Each MyCellE In ws.Range("E2:E" & ERow)
                            If MyCellA = 2 And MyCellB = 3 And MyCellC = "F" And MyCellD = 1 And MyCellE = 1 Then
                                MsgBox "Category 1 Achieved!"
                            End If
                    Next MyCellE
                Next MyCellD
            Next MyCellC
        Next MyCellB
    Next MyCellA
    
End Sub

【问题讨论】:

  • 您只需要一个循环 - 依次获取每一行并在该行上运行检查。
  • 嘿蒂姆,晚安!谢谢你的帮助,伙计。但我看不出单个循环如何解决这个问题。由于我需要为每行验证 5 个不同列中的 5 个条件以创建一个类别,例如 1-1-J-1-1(稍后我将使用此模式将所有行复制到另一张表),我怎么能用一个循环做到这一点?请你为我举个例子好吗?谢谢!

标签: excel vba loops filter


【解决方案1】:

您只需要一个循环 - 依次获取每一行并在该行上运行检查。

像这样:

Sub Test()

    Dim ws As Worksheet
    Dim ARow As Long, rw As Long
    
    Set ws = ThisWorkbook.Sheets("base")
    ARow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
    
    For Each rw In ws.Range("A2:E" & ARow).Rows
        
        'Test the relevant cells on the row for the required values
        If rw.Cells(1).Value = 2 Then
            If rw.Cells(2).Value = 3 Then
                If rw.Cells(3).Value = "F" Then
                    If rw.Cells(4).Value = 1 Then
                        If rw.Cells(5).Value = 1 Then
                            MsgBox "Category 1 Achieved!"
                        End If
                    End If
                End If
            End If
        End If
           
    Next rw

End Sub

请注意,如果您只是 AND 将所有检查放在一起,它会明显变慢,因为即使第一个单元格可能不符合您的标准,也需要读取所有 5 个单元格。

【讨论】:

  • 哇哦,非常感谢,蒂姆,它工作得很好!你救了我 =D 祝你有美好的一天!
  • ++ 做得很好。我想知道为什么不使用And 加入所有Ifs
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 2021-12-20
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
相关资源
最近更新 更多