简体   繁体   中英

VBA code to compare cell values

I have 3 worksheets(base) and a master worksheet (master) to compare with.

For each base worksheet, I need to compare the string value in each row for Col H (eg) to each row in master worksheet for Col G (eg). If the string value does not exist in the whole col G, the row in the base worksheet must be copied over to the master worksheet.

TIA!

I think its easy enough the use the worksheet function Match which will error if the items doesn't exist so we handle the error. Here's my answer:

Sub MyCompare()
    Dim wksMaster As Worksheet
    Dim wksBases(2) As Worksheet
    Dim wksBase As Variant
    Dim intRowCountBase As Integer
    Dim intRowCountMaster As Integer
    Dim rngCell As Range
    Dim rngMasterColG As Range
    Dim intMatch As Integer

    'set up sheet vaiables
    Set wksMaster = ActiveWorkbook.Worksheets("Master")
    Set wksBases(0) = ActiveWorkbook.Worksheets("Base1")
    Set wksBases(1) = ActiveWorkbook.Worksheets("Base2")
    Set wksBases(2) = ActiveWorkbook.Worksheets("Base3")

    'get the range of the master sheet col G
    intRowCountMaster = wksMaster.UsedRange.Rows.Count
    Set rngMasterColG = wksMaster.Range(wksMaster.Cells(1, 7), wksMaster.Cells(intRowCountMaster, 7))

    'Loop through the base sheets
    For Each wksBase In wksBases
        intRowCountBase = wksBase.UsedRange.Rows.Count

        'Loop through the cells in col H of the base sheet
        For Each rngCell In wksBase.Range(wksBase.Cells(1, 8), wksBase.Cells(intRowCountBase, 8))
            If rngCell.Value <> "" Then 'only do something if there is a value in the base sheet
                On Error Resume Next
                'the match value will error if the item doesn't exist
                intMatch = Application.WorksheetFunction.Match(rngCell.Value, rngMasterColG, 0)
                If Err.Number > 0 Then ' ie there is no match
                    On Error GoTo 0

                    intRowCountMaster = intRowCountMaster + 1
                    'put the item on the master sheet
                    wksMaster.Cells(intRowCountMaster, 7).Value = rngCell.Value
                    'reset the master range
                    Set rngMasterColG = wksMaster.Range(wksMaster.Cells(1, 7), wksMaster.Cells(intRowCountMaster, 7))
                End If
            End If
        Next rngCell

    Next wksBase

End Sub

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