首页 文章

比较具有相似/不同值的单元格

提问于
浏览
0

我在比较具有不同值的单元格时遇到问题,但如果比较的值相同则可行 . 我面临的问题是比较工作表1中的单元格A1:A100和工作表2中的单元格B3:B1000 . 如果工作表1和工作表2中的值相等,它将粘贴到工作表3中的单元格A,我能够做到 . 如果值不相等,它将粘贴到工作表3中的单元格B,这是我面临的问题 . 这是我的代码 .

Private Sub CommandButton1_Click()

Dim val1,val2 As String

对于i = 1到100

val1 =工作表(“Sheet1”) . 单元格(i,1)

For j = 3 To 1000
 val2 = Worksheets("Sheet2").Cells(j, 2)

  If (val1 = val2) Then
   Worksheets("Sheet3").Cells(i, 1) = val2

  ElseIf (val1 <> val2) Then
   Worksheets("Sheet3").Cells(i, 2) = val2

  End If

  Next

下一个

结束子

1 回答

  • 0

    你实际上是指.....“对于表2中B列中的每一个值,如果找到这个值 within the range A1:A100”......

    终于搞定了 . 看看这是否有帮助 .

    Sub test()
        Dim val As Variant
        Dim found As Integer, notFound As Integer
    
        found = 0
        notFound = 0
    
        For j = 3 To 1000
            val = Worksheets("Sheet2").Cells(j, 2).Value
            If Not IsError(Application.Match(val, Worksheets("Sheet1").Range("A1:A100"), 0)) Then
                'Comment this line if you don't want to paste the values that are the same
                'Worksheets("Sheet3").Range("A1").Offset(found) = val
                found = found + 1
            Else
                Worksheets("Sheet3").Range("B1").Offset(notFound) = val
                notFound = notFound + 1
            End If
        Next
    End Sub
    

相关问题