简体   繁体   中英

Counting the associated value in the same row of another value in Excel-VBA

I have problem in counting the values which are in the same row as the identified value. The table should display the same exact value shown at the image bellow. Generating a table that shows how many times these values are associated with each other. Heres what I got so far my code is really messy and im not really good at excel vba:

Sub Button1_Click()  Dim cell As Range, f As Range
Dim rowOffset As Long

With Worksheets("Sheet1").Range("A3:F2000") '<--| change this to your actual range of interest

    For Each cell In .SpecialCells(xlCellTypeConstants, xlNumbers)

        rowOffset = 0 '<--| rowOffset was once set to 1

        Set f = .Find(what:=cell, after:=cell, LookIn:=xlValues, lookat:=xlWhole, searchdirection:=xlPrevious)

        If Not f Is Nothing And f.Row <= cell.Row Then rowOffset = cell.Row - f.Row '<--| if Data has occurred is assumed, add + 1 after this line of codes here.

        Worksheets("gapByRow").Cells(cell.Row, cell.Column).Value = rowOffset

    Next cell
End With End Sub

The example bellow has a table that shows the times a value is associated. The cell with a Yellow background are the “Identified values” and the one with the Green are the associates. As you can see 8 on the yellow background has values right beside which is 5, 1, 0, 0, 3, 2, 5, 7 and etc. This means that 8 is associated by 1 in 5 times, 2 in 1 time, 3 in 0, 4 in 0, 5 in 3, 6 in 2 and so on. if the vba code is correct it should display the same result here.

范例图片

Instead of a button I would make it a UDF, then it can be called like a formula:

Function MyCount(Rng As Range, xVal, Yval)
Application.Volatile
Dim rngArr() As Variant
rngArr = Rng.Value
For i = 1 To UBound(rngArr, 1)
    For j = 1 To UBound(rngArr, 2)
        If rngArr(i, j) = xVal Then
            For k = 1 To UBound(rngArr, 2)
                If rngArr(i, k) = Yval Then MyCount = MyCount + 1
            Next k
        End If
    Next j
Next i

End Function

You would place this in I3:

=MyCount($A$3:$F$17,$H3,I$2)

Then copy over and down the matrix.

在此处输入图片说明

I would then make the calculation manual and hit F9 after the data is updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM