0

I am trying to make a UDF in VBA that takes multiple arrays of equal size as an argument and then loops through them staying at the same index for each array.

I have set the code up as follows.

Public Function TwoArrays(TargetRange(), CriteriaRange())
dim value as range
for each value in TargetRange

next
end function

The issue is I can't get the index of the TargetRange to use in the CriteriaRange and even if I could for whatever reason whenever I put something like

CriteriaRange(2)

I get an error instead of what happens to be within that index.

Is there a way I can get the UDF to treat the array like a normal VBA array where I can do something along the lines of


Public Function TwoArrays(TargetRange(), CriteriaRange())
dim result as range
for i = lowerbound(TargetRange) to ubound(TargetRange)
     If CriteriaRange(i) > 0 then
           result = result + TargetRange(i)
     end if
next i
end function

Thank you!

3
  • 1
    You seem to be conflating Ranges and arrays. Probably worth reading cpearson.com/excel/ArraysAndRanges.aspx Commented Jun 10, 2021 at 13:07
  • Even removing the "as range" or changing it to something else doesn't impact my problem. Commented Jun 10, 2021 at 14:00
  • RIght, because a Variant array from a Range is 2D and you shouldn't be using a For Each loop ... did you read the referenced link? Commented Jun 10, 2021 at 14:01

1 Answer 1

1

Like this:

Public Function TwoArrays(TargetRange As Range, CriteriaRange As Range)
    Dim result, arrT, arrC, r As Long, c As Long
    arrT = TargetRange.Value
    arrC = CriteriaRange.Value
    
    'probably should add some code here to check both ranges are the same size...
    
    For r = 1 To UBound(arrT, 1)
        For c = 1 To UBound(arrT, 2)
            If arrC(r, c) > 0 Then result = result + arrT(r, c)
        Next c
    Next r
    TwoArrays = result
End Function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.