VBA返回符合多个条件的所有结果

时间:2020-10-21 10:27:54

标签: excel vba

我正在尝试制作至少匹配2个条件的VBA代码。 我想返回C列为“ ACMA”而T列为“ 0”的行。

enter image description here

它应该在其他表中列出如下:

enter image description here

我尝试了Internet上的每个公式以及其他用户的代码,但是它不起作用。您能以适当的方式提供我吗?

1 个答案:

答案 0 :(得分:0)

就像@CLR提到的那样,您需要检查T列是否返回0,因为它是空的还是因为实际上是0。对于此解决方案,我检查了单元格<> 0(即空)中值的长度。 / p>

Sub ReturnMatches()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow1 As Long, newRow2 As Long
Dim x As Long

'don't know the names of your sheets so adjust accordingly
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")

'determine last row of data sheet
lastRow1 = ws1.Cells(ws1.Rows.Count, 3).End(xlUp).Row

For x = 2 To lastRow1
    
    'check to see if it is a match
    'for T, also check length of value in cell <> 0 (i.e. blank)
    If _
        ws1.Cells(x, 3) = "ACMA" And _
        ws1.Cells(x, 20) = 0 And Len(ws1.Cells(x, 20).Value) <> 0 Then
        
        'define first blank row of 2nd sheet
        newRow2 = ws2.Cells(ws1.Rows.Count, 1).End(xlUp).Row + 1
        
        'copy matching information to first blank row
        ws2.Cells(newRow2, 1) = "ACMA"
        ws2.Cells(newRow2, 2) = ws1.Cells(x, 4)
        
    End If
    
Next x

End Sub