比较非连续范围值和计数值出现次数

时间:2018-01-31 20:47:42

标签: vba excel-vba excel

我试图比较非连续范围的值,然后记下相同值出现的数字

enter image description here

我使用了上一篇文章中的代码,但它只比较了相同范围的值

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

1 个答案:

答案 0 :(得分:0)

尝试此功能

Function COUNT_THIS_VALUE(ByRef CountThis As Range, ByRef InthisRange As Range) As Double

Dim AddressArray() As String
Dim i As Double
AddressArray = Split(InthisRange.Address(False, False), ",")

For i = 0 To UBound(AddressArray) Step 1
    COUNT_THIS_VALUE = COUNT_THIS_VALUE + Application.WorksheetFunction.CountIf(Range(AddressArray(i)), CountThis.Value)
Next i
End Function

函数的第一个参数是你要计算的内容。它必须是单个细胞。函数的第二个参数位于您要搜索的范围内。

我做了一个简单的表,其中随机值介于1和10之间。黄色行是我的Range1,白色行是我的Range2。我计算了每个范围内从1到10的所有数字并做了一个表。看一下图像以便更好地理解。

enter image description here

希望这有帮助!