Макросы для суммирования уникальных значений, связанных с другим столбцом - PullRequest
0 голосов
/ 30 мая 2018

Мне нужно создать макросы для заполнения во вкладке «Калькулятор метрик», сумма «Нет шагов теста» (столбец G) для каждого «исследования» (столбец D).Сумма должна учитывать только уникальные значения.Пожалуйста, смотрите таблицу ниже: Table

В этом исследовании нет «1111», общий шаг № / пациент № 20 повторяется 3 раза, «15» повторяется 4 раза и «30» 3 раза - iнужно, чтобы макросы просто взяли уникальные значения и добавили их, т. е. просто 20 + 15 + 30 = 65.

На вкладке «Калькулятор метрик».шаги 1111 65

1 Ответ

0 голосов
/ 30 мая 2018

Так что, если я понимаю вопрос, вы хотите суммировать уникальные значения в столбце B. Следующее поможет.

Обратите внимание, что вам нужно будет настроить диапазон по мере необходимости.Прямо сейчас диапазон установлен на B2: B20, как в вашей таблице сэмплов.

Sub unique()
    Dim arr() As Variant
    Dim arrElem As Variant
    Dim Rng As Range
    Dim elem As Range
    Dim i As Long
    Dim stepSum As Long
    Dim match As Boolean

    Set Rng = Range("B2:B20") 'Edit this so that it fits your array

    'this sets up an array to store unique variables
    ReDim Preserve arr(1 To 1) As Variant
    arr(1) = 0

    'this loops through each number in the identified range
    For Each elem In Rng

      'this is a boolean, false means the current number is unique (so far) true means the number has been seen previously.
      match = False

      'this checks the current number against all the unique values stored in the array
      For Each arrElem In arr
          'If it finds a match, it changes the boolean to true
          If arrElem = elem Then match = True
      Next arrElem

      'If not match was found, we store the current number as a new unique value in the array
      If match = False Then
        'this adds another row to the array
        ReDim Preserve arr(1 To UBound(arr) + 1) As Variant
        'this adds the unique value
        arr(UBound(arr)) = elem.Value
      End If

    Next elem

    'this sums the unique numbers we stored in the array
    For i = 1 To UBound(arr)
        stepSum = stepSum + arr(i)
    Next i

    'this reports the sum of unique elements
    MsgBox stepSum

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...