Как сравнить несколько строковых переменных для суммирования данных в VBA? - PullRequest
0 голосов
/ 23 апреля 2019

В моем прогнозе я прогнозирую сразу несколько объектов в Excel. Для некоторых объектов я должен рассчитать некоторые части PL и BS в несколько итераций из-за структуры моих данных.

Когда я закончил прогнозирование, я сбрасываю результаты в лист FC_OUTPUT и хочу группировать / суммировать данные вместе, когда отношение сущность (столбец D), GREN (столбец H) и IC (столбец I) совпадает. , Код будет циклически проходить по строкам, и если он найдет совпадение, он должен сложить строки вместе и удалить добавленную строку. Ниже вы можете найти мой код. Майкл Мерфи (https://stackoverflow.com/users/8826022/michael-murphy)) сделал меня отличным фрагментом кода, чтобы преодолеть большинство моих недостатков, которые я сделал в предыдущем коде. К сожалению, я все еще борюсь с двумя ключевыми аспектами: 1. Для сортировки ICCol я получаю сообщение об ошибке «1004»: метод «Range» объекта «_Global» не обработан. Почему сортировка двух других столбцов работает отлично. 2. Добавление значений строки от столбца 12 до столбца 96, не работает. Я немного не в своей тарелке с этим, и вся помощь очень ценится.

Sub itest()

Dim EntityCol As Long, GRENCol As Long, ICCol As Long, ValueCol As Long, i As Long
Dim firstrow As Long, lastrow As Long, rngData As Range

Worksheets("FC_OUTPUT").Activate
Application.ScreenUpdating = False

EntityCol = 4 ' column D
GRENCol = 8
ICCol = 9
ValueCol = 12 ' column L
firstrow = 7
lastrow = Cells(Rows.Count, EntityCol).End(xlUp).Row

With ActiveSheet.Sort
     .SortFields.Add Key:=Range(Cells(firstrow, EntityCol)), Order:=xlAscending
     .SortFields.Add Key:=Range(Cells(firstrow, ICCol)), Order:=xlAscending
     .SortFields.Add Key:=Range(Cells(firstrow, GRENCol)), Order:=xlAscending
     .SetRange Range(Cells(firstrow, 1), Cells(lastrow, 96))
     .Header = xlNo
     .Apply
End With


Set rngData = Range(Cells(firstrow, 1), Cells(lastrow, 96)) ' this line should be adjusted but you'll need to also adjust firstrow and lastrow

With rngData
' Here I'll start a loop for every row going from the end to the beginning, to prevent issues when removing rows
    For i = lastrow To firstrow Step -1
    ' Here I'll use the If statement to check if the values are the same as the previous row

        If .Cells(i, EntityCol) = .Cells(i - 1, EntityCol) And _
                .Cells(i, GRENCol) = .Cells(i - 1, GRENCol) And _
                .Cells(i, ICCol) = .Cells(i - 1, ICCol) Then
            ' This is where you'll do your addition and delete
            .Cells(i - 1, ValueCol).Value2 = .Cells(i - 1, ValueCol) + .Cells(i, ValueCol)
            .Rows(i).Delete
        End If
    Next i
End With

End Sub

1 Ответ

0 голосов
/ 23 апреля 2019

Вам нужно будет поиграться с диапазоном и перепроверить номера столбцов, чтобы убедиться, что они соответствуют вашим данным, но это пример того, как я справлюсь с вашей задачей. Может быть, это поможет вам в лучшем направлении. Это предполагает, что данные отсортированы правильно, и строго сравнивает каждую строку с предыдущей строкой:

Sub itest()

Dim EntityCol As Long, GRENCol As Long, ICCol As Long, ValueCol As Long, i As Long
Dim firstrow As Long, lastrow As Long, rngData As Range

EntityCol = 4 ' column D
GRENCol = 8
ICCol = 9
ValueCol = 12 ' column L
firstrow = 7
Set rngData = Cells ' this line should be adjusted but you'll need to also adjust firstrow and lastrow
' To find the last row, I'm assuming that your Entity column has values all the way to the end of your data
lastrow = Cells(Rows.Count, EntityCol).End(xlUp).Row

With rngData
' Here I'll start a loop for every row going from the end to the beginning, to prevent issues when removing rows
    For i = lastrow To firstrow Step -1
    ' Here I'll use the If statement to check if the values are the same as the previous row
        If .Cells(i, EntityCol) = .Cells(i - 1, EntityCol) And _
                .Cells(i, GRENCol) = .Cells(i - 1, GRENCol) And _
                .Cells(i, ICCol) = .Cells(i - 1, ICCol) Then
            ' This is where you'll do your addition and delete
            .Cells(i - 1, ValueCol).Value2 = .Cells(i - 1, ValueCol) + .Cells(i, ValueCol)
            .Rows(i).Delete
        End If
    Next i
End With

End Sub

Вот мои тестовые данные в начале: Before

И после запуска: After

...