Excel VBA-比较列以进行匹配

时间:2017-12-22 23:38:44

标签: excel vba excel-vba

您好我正在尝试比较同一个Excel工作表上的两个表。以下是我想要实现的目标。这必须在excel VBA中完成。

If A matches F (Equipment numbers match)
AND
If B matches G (ID-Numbers match)
AND 
If column C=1 (Equipment is in Service. C=0 means not in service)

Then
Update (copy/ paste) Column H with value in D (Update Inspection intervals from column D into H)

But 
If A doesn’t match F (Equipment numbers DO NOT match)
AND/ OR 
If B doesn’t match G (ID-Numbers DO NOT match)

Highlight the cell in column A

任务1

If A matches F (Equipment numbers match)
AND
If B matches G (ID-Numbers match)
AND 
If C=1 (Equipment is in Service. C=0 means not in service)
AND
If Column I (Inspection Due date) has a red OR Pink Cell highlighted 

Then
Update Column J with E (Update Inspection date (J) with Last Inspection date (E))

任务2

IN A

1 个答案:

答案 0 :(得分:0)

编辑:在您在评论中提供的进一步信息后,我调整了下面的代码,现在应该适用于任务1,然后调整我为任务2显示的内容:

Sub Task_1()
    Dim X As Integer, Y as Integer, LastX as Integer
    For X = 2 to 10000
        If Range("A" & X).Value = "" Then Exit For
    Next X
    LastX = X - 1
    For X = 2 to LastX
        For Y = 2 to LastX
            If Range("F" & Y).Value = Range("A" & X).Value Then
                If Range("G" & Y).Value = Range("B" & X).Value Then
                    If CInt(Range("C" & X).Value) = 1 Then 
                        Range("H" & Y).Value = Range("D" & X).Value
                        GoTo Found_It
                    End If
                End If
            End If
        Next Y
        Range("A" & X).Interior.Color = vbCyan
Found_It:
    Next X
End Sub

编辑:Task_2代码的问题是:1。您不能将两个End Sub作为一个Sub例程的结尾。 2.对于任何具有多行的If Then语句,您必须具有End If。 3.您可以组合And参数以减少嵌套Ifs的数量。 4.您可以使用括号命名变量(括号为数组值保留)。以下内容现在应该有效。

Sub Task_2()
    Dim X As Integer, Y As Integer, LastX As Integer
    Dim RGB1 As Long, RGB2 As Long

    RGB1 = RGB(255, 153, 204)
    RGB2 = RGB(255, 0, 0)

    For X = 2 To 10000
        If Range("B" & X).Value = "" Then Exit For
    Next X
    LastX = X - 1
    For X = 2 To LastX
        For Y = 2 To LastX
            If Range("W" & Y).Value = Range("B" & X).Value And Range("N" & Y).Value = Range("D" & X).Value And CInt(Range("E" & X).Value) = 1 Then
                If Range("I" & Y).Interior.Color.RGB = RGB1 Or Range("I" & Y).Interior.Color.RGB = RGB2 Then
                    Range("J" & Y).Value = Range("E" & X).Value
                    GoTo Found_It_2
                End If
            End If
        Next Y
        Range("B" & X).Interior.Color = vbCyan
Found_It_2:
    Next X
End Sub