简体   繁体   中英

vba macro to compare two columns in excel?

I am trying to compare QTY and UID in one sheet ( Shipment ) to another sheet ( Record ). I am trying to compare if the UID is equal then compare the QTY , if the QTY is equal then output "Complete" else "Incomplete" besides the record in the Record sheet.

Sheet Record

UID qty Shipped
234 2   incomplete
335 5   
453 6   
664 3   complete
787 13  

Sheet Shipment

UID qty
664 3
234 1

Assuming your Sheet Shipment is as follows

在此处输入图片说明

Then in Cell C2 of Sheet Record enter the following formula

=IFERROR(IF(INDEX($A$2:$A$6,MATCH(1,(A2=Shipment!$A$2:$A$3)*1,0)),IFERROR(IF(INDEX($A$2:$A$6,MATCH(1,(B2=Shipment!$B$2:$B$3)*1,0)),"Complete"),"Incomplete"),""),"")

This is an array formula so commit it by pressing Ctrl + Shift + Enter . Drag/Copy down as required.See image for reference.

在此处输入图片说明

A non Array formula that allows full column references and entered as normal:

=IF(ISNUMBER(MATCH(A2,Shipment!A:A,0)),IF(COUNTIFS(Shipment!A:A,A2,Shipment!B:B,B2),"Complete","Imcomplete"),"")

在此处输入图片说明


Or this shorter version:

=IFERROR(IF(INDEX(Shipment!B:B,MATCH(A2,Shipment!A:A,0)) = B2,"Complete","Imcomplete"),"")

You cannot have both the value and a formula in the same cell. You will need VBA for what you are trying to achieve.

Try this..

Sub GetQtyStatus()
Dim sws As Worksheet, dws As Worksheet
Dim Rng As Range, Cell As Range
Dim lr As Long, r As Long

Application.ScreenUpdating = False

Set sws = Sheets("Shipment")
Set dws = Sheets("Record")
lr = dws.Cells(Rows.Count, 1).End(xlUp).Row
Set Rng = dws.Range("A2:A" & lr)

For Each Cell In Rng
    If Application.CountIf(sws.Columns(1), Cell.Value) > 0 Then
        r = Application.Match(Cell.Value, sws.Columns(1), 0)
        If Cell.Offset(0, 1) = sws.Cells(r, 2) Then
            Cell.Offset(0, 2) = "Complete"
        Else
            Cell.Offset(0, 2) = "Incomplete"
        End If
    End If
Next Cell

Application.ScreenUpdating = True
End Sub

How to implement the code:

  1. Open your workbook and press Alt + F11 to open VB Editor.
  2. On VB Editor --> Insert --> Module and paste the code give above into the opened code window.
  3. Close VB Editor and save your workbook as Macro-Enabled Workbook.

How to run the code:

  1. Press Alt + F8 to open Macro window.
  2. Choose the macro GetQtyStatus and click on Run.

The code assumes that there are two sheets called Record and Shipment in the workbook and UID and Qty are listed in column A and B respectively on both the sheets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM