我在比较具有不同值的单元格时遇到问题但是如果比较的值相同则它有效。我面临的问题是比较工作表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
下一步
End Sub
答案 0 :(得分:0)
你实际上是指......“对于工作表2中B列中的每个值,如果发现在范围内 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