VPA program for compare values in array and give a result (MS Excel)

瘦欲@ 提交于 2019-12-12 04:14:22

问题


I have some variables in an array. Those may be "Yes", "No", "NA" or "-". For example i have an array arr(1 t0 5) . The values would be 'Yes, Yes, No, No & Yes'. The length of array may vary. Like these the combination may vary given that above four values ("Yes", "No", "NA" or "-") My requirement is that i want to compare the values in array and give a result in a cell of excel work sheet. For example, if all values in array are either 'Yes' or 'NA' then result should be "Yes". If any one value is 'No' or '-' then result should be "No".


回答1:


You can use Application.Match to find if you have at least 1 "No" in your arr array.

Option Explicit

Sub CheckArray()

Dim arr As Variant
Dim Res As Variant, r As Variant
Dim Result As String   

' test #1: at least 1 "No" or "-"  in array
arr = Array("Yes", "-", "Yes", "NA", "Yes")

Res = Application.Match(Array("No", "-"), arr, 0)
For Each r In Res
    Result = "Yes" ' init value
    If Not IsError(r) Then ' <-- at least 1 result of "-" or "No" found
        Result = "No"
        Exit For
    End If
Next r    
' === The result is "No" ===


' test #2: there are no "No" or "-" in the array
arr = Array("Yes", "NA", "Yes", "NA", "Yes")

Res = Application.Match(Array("No", "-"), arr, 0)
For Each r In Res
    Result = "Yes" ' init value
    If Not IsError(r) Then ' <-- at least 1 result of "-" or "No" found
        Result = "No"
        Exit For
    End If
Next r

' === The result is "Yes" ===

End Sub


来源:https://stackoverflow.com/questions/42903181/vpa-program-for-compare-values-in-array-and-give-a-result-ms-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!