Excel VBA-比较列以进行匹配

问题描述 投票:-1回答:1

你好我想在同一个excel表上比较两个表。以下是我想要实现的目标。这必须在excel VBA中完成。

A   B   C   D       E           F   G   H       I        J         
E1  40  1   4   4/16/2017       E4  30       11/1/2017
E2  20  1   5   6/22/2016       E2  20       11/1/2017
E3  10  0   4   6/30/2017       E1  40       10/31/2017
E4  30  1   6   3/10/2015       E3  10       10/31/2017

任务1

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

任务2

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))
excel vba excel-vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.