Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

Compare 2 cells in different sheets in VBA(Excel 2010)

Hi Can I ask for a sample macro code to compare 2 different columns from 2 different sheets.

Here's the columnA in sheet1

enter image description here

Here's the column A in sheet2 enter image description here

Here's what I need to make as an output in sheet1

enter image description here

Then all cells in column A sheet1 without match such as red in the picture above should be cut and copied in column C in sheet1 like the below enter image description here

lastly all cells in column A sheet 2 that has no match should be cut as well and pasted in column D in sheet 1 such as ABC:PINK, ABC:VIOLET and ABC:BLACK as shown below

enter image description here

Thanks for the help in advance.

Here's what I got so far

Sub Button1_Click()
On Error GoTo ErrorHndler:
Dim myRange As Range
Dim sRng As Range

Set myRange = Range("A1:A50")

Start:
     For Each sRng In myRange
       If sRng Like Sheets("Sheet2").Range("A1").Value Then
          MsgBox (Sheets("Sheet2").Range("A1").Value) <----it does not pass here 
          (----I have no Idea what to put here-----)
          'GoTo NextCell
       Else
          'GoTo Start
          MsgBox (Sheets("Sheet2").Range("A1").Value)
          'MsgBox "Doesn't match"  <-----for debugging purposes
       End If
 NextCell:
 Next sRng

 ErrorHandler:
 MsgBox ""
 End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can search a range for a value using Range.Find

Range.Find returns Nothing if no match is found or a Range if a match is found.

You can check if two objects refer to the same object using the is operator.

Here is an example:

Sub lookup()
    Dim TotalRows As Long
    Dim rng As Range
    Dim i As Long

    'Copy lookup values from sheet1 to sheet3
    Sheets("Sheet1").Select
    TotalRows = ActiveSheet.UsedRange.Rows.Count
    Range("A1:A" & TotalRows).Copy Destination:=Sheets("Sheet3").Range("A1")

    'Go to the destination sheet
    Sheets("Sheet3").Select

    For i = 1 To TotalRows
        'Search for the value on sheet2
        Set rng = Sheets("Sheet2").UsedRange.Find(Cells(i, 1).Value)
        'If it is found put its value on the destination sheet
        If Not rng Is Nothing Then
            Cells(i, 2).Value = rng.Value
        End If
    Next
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...