Функция оценки / MATCH в VBA не работает при сравнении нескольких критериев - PullRequest
0 голосов
/ 26 января 2019

Я искал в интернете решение этой проблемы.

У меня есть списки, которые должны совпадать и должны сравниваться на взаимной основе. Мне нужно сравнить около 5 разных переменных в каждой строке, а затем с помощью функции MATCH идентифицировать первую подходящую строку, которая затем удаляется. Затем я буду перебирать список, пока не останутся записи, которые не были удалены. Причина, по которой мне нужно удалить, заключается в том, что в каждом списке может быть несколько совпадений, но если в одном списке 3, а в другом - 4, мне потребуется 4-я (дополнительная) запись для идентификации.

Пожалуйста, критикуйте код, который у меня есть ниже, мне еще предстоит создать цикл, так как я думаю, что это будет легко, как только я получу функцию MATCH для точной работы. Стандартная формула CSE работает на листе, но мне нужен VBA для возможности зацикливания. Спасибо.

Я пытаюсь проверить значение RowDelete с помощью msgbox и возвращаю ошибку времени выполнения 13: «несоответствие типов». Я также попытался использовать окно WATCH, чтобы увидеть, какой результат передан, но сама формула, похоже, не работает.

РЕДАКТИРОВАТЬ: Этот код возвращает ошибку во время выполнения «13»: несоответствие типов. Я не могу решить это. Я просто хотел бы знать, что я могу сделать, чтобы передать формулу результат, который я могу использовать (в данном случае первый результат - строка 62). После этого я смогу сделать все самостоятельно.

Sub DeleteMatches2()

    Dim Ws As Worksheet
    Dim Direction As String
    Dim OrderType As String
    Dim Amount As String
    Dim CCY As String
    Dim Rate As String

    Dim RowCt As Long
    Dim Formula As Integer

    Dim iRow As Long

    Dim colNum As Integer

    Dim RowDelete As Long

    Set Ws = Sheets("KOOLTRA RAW")

    With Ws
        RowCt = .Cells(.Rows.Count, 11).End(xlUp).Row - 1

        For iRow = 2 To RowCt

            Direction = .Cells(iRow, "K").Value
            OrderType = .Cells(iRow, "L").Value
            Amount = .Cells(iRow, "M").Value
            CCY = .Cells(iRow, "N").Value
            Rate = .Cells(iRow, "P").Value

            Formula = Evaluate("MATCH(1,(""" & OrderType & """ = B:B)*(""" & Direction & """ = C:C)*(""" & Amount & """ = D:D)*(""" & CCY & """ = E:E)*(""" & Rate & """ = H:H),0)")
            MsgBox Formula

            Exit For

        Next iRow
    End With
End Sub

1 Ответ

0 голосов
/ 26 января 2019

Я прокомментировал ваш код в надежде, что мои комментарии помогут вам улучшить его.

Sub DeleteMatches()

    Dim Ws As Worksheet
    Dim Direction As Variant
    Dim OrderType As Variant
    Dim Amount As Variant
    Dim CCY As Variant
    Dim Rate As Variant
    Dim RowCt As Long                       ' rows and columns should be of Long type
    Dim Formula As Variant
    Dim iRow As Long
    Dim colNum As Long
    Dim RowDelete As Long

    Set Ws = Sheets("Example")                      ' don't "select" anything

    With Ws
        ' creating variable for toral rows to cycle through:-
        ' you aren't "creating" a variable.
        ' RowCt is the variable and you are assigning a value to it.
        RowCt = .Cells(.Rows.Count, 11).End(xlUp).Row - 1

        For iRow = 2 To RowCt                       ' loop through all rows
            ' assigning a Range to a Variant (Direction etc) assigns the
            ' Range object to the variant. I have modified the code
            ' to assign the specified cell's value to the variant.
            ' A Variant can be anything. It would be better if you
            ' would declare your variables as String or Double or Integer or Long.
            Direction = .Cells(iRow, "K").Value     ' Range("K" & iRow)
            OrderType = .Cells(iRow, "L").Value     ' Range("L" & iRow)
            Amount = .Cells(iRow, "M").Value        ' Range("M" & iRow)
            CCY = .Cells(iRow, "N").Value           ' Range("N" & iRow)
            Rate = .Cells(iRow, "P").Value          ' Range("P" & iRow)

            ' Formula is a property of the Range object.
            ' use like .Cells(iRow, "X").Formula = "MATCH(1,((B:B="" & OrderType & "") ......
'            Formula = "MATCH(1,((B:B="" & OrderType & "")*(C:C="" & Direction & "")*(D:D="" & Amount & "")*(E:E="" & CCY& "")*(H:H="" & Rate & "")),0)"
            ' To set a formula, you need to enter the = sign, like
            ' .Cells(iRow, "X").Formula = " = MATCH(1 ...
            ' it is best that you test the formula on the worksheet
            ' before attempting to let VBA write it to a cell.
            ' Your above formula looks like nothing Excel would be able to execute.

            ' Please read up on how to use the Evaluate function.
            ' It can't do what you appear to expect it to do.
'            RowDelete = Evaluate(Formula)

            MsgBox RowDelete

            'colNum = Application.Match(1,((B1:B2=OrderType)*(C1:C2=Direction)*(D:D=Amount)*(E:E=CCY)*(H:H=Rate)),0)
            ' I think it is the better idea to let VBA execute the MATCH function
            ' rather than writing the formula to the worksheet.
            ' However, your "code" has no similarity with what MATCH can do.
            ' Read up on how to use the the MATCH function correctly.
            ' When executed by VBA it needs the same syntax as when called from the worksheet.


            'Formula = "MATCH(1,((B:B=OrderType)*(C:C=Direction)*(D:D=Amount)*(E:E=CCY)*(H:H=Rate)),0)"
            'Formula = "MATCH(1,((B:B=L2)*(C:C=K2)*(D:D=M2)*(E:E=N2)*(H:H=P2)),0)"
            'colNum = Worksheets("Example").Evaluate("MATCH(1,((B:B=OrderType)*(C:C=Direction)*(D:D=Amount)*(E:E=CCY)*(H:H=Rate)),0)")

            Exit For            ' stop the loop here during testing
                                ' remove this stop after your code works
        Next iRow
    End With
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...