我需要比较excel表中两个范围的值,如果发现值等于第二个范围中的另一个值,我会在靠近该值的单元格中写入数字1,依此类推将每个数字增加1找到了价值。
Sub tbl()
Dim Range1 As Range
Set Range1 = Worksheets("Sheet1").Range("A1:C10")
Dim Range2 As Range
Set Range2 = Worksheets("Sheet2").Range("A1:A10")
Dim cel As Range
Dim x As Integer
Dim i, j As Integer
For j = 1 To Range1.Count
For i = 1 To Range2.Count
If Range1(j).Value = Range2(i).Value Then
x = x + 1
Dim cel3 As Range
Set cel3 = Range(Range2(i).Address)
cel3.Offset(0, 1).Value = x
End If
Next i
Next j
End Sub
答案 0 :(得分:1)
加载值以搜索数组并在另一个范围内使用COUNTIF()以避免其中一个循环。
Sub tbl()
Dim Range1 As Range
Dim Range2 As Variant
Dim range3() As Variant, j As Long
Set Range1 = Worksheets("Sheet1").Range("A1:C10")
Range2 = Worksheets("Sheet2").Range("A1:A10")
ReDim range3(1 To UBound(Range2, 1), 1 To 1)
For j = 1 To UBound(Range2, 1)
range3(j,1) = Application.WorksheetFunction.CountIf(Range1, Range2(j,1))
Next j
Worksheets("Sheet2").Range("B1").Resize(UBound(range3), 1).Value = range3
End Sub