簡體   English   中英

計算Excel-VBA中另一個值的同一行中的關聯值

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

我在計算與已識別值在同一行中的值時遇到問題。 該表應顯示與下面的圖像相同的精確值。 生成一個表,顯示這些值相互關聯的次數。 到目前為止,我得到的繼承人代碼非常混亂,而且我不太擅長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

下面的示例具有一個表,該表顯示了關聯值的時間。 帶有黃色背景的單元格是“標識的值”,帶有綠色的單元格是關聯的。 如您所見,在黃色背景上有8個值,其旁邊分別是5、1、0、0、3、2、5、7等。這意味着8與5分之一相關,2與1次相關, 3 in 0、4 in 0、5 in 3、6 in 2等等。 如果vba代碼正確,則應在此處顯示相同的結果。

范例圖片

我可以將它改為UDF,而不是按鈕,然后可以將其稱為公式:

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

您可以將其放在I3中:

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

然后上下復制矩陣。

在此處輸入圖片說明

然后,我將制作計算手冊,並在數據更新后按F9鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM