I am currently working on a UDF which returns and concatenates the headers if it is greater than and less than to a specific value. I’m not really good in Excel-Vba and what I got so far is this pathetic code which I couldn’t understand anymore. I would truly appreciate it if someone could help. Here's what i got so far:
Public Function greaterLessValue(Rng As Range, Rng2 As Range, greater, less)
Dim rngArr() As Variant
rngArr = Rng.value
For i = 1 To UBound(rngArr, 1)
For j = 1 To UBound(rngArr, 2)
If rngArr(i, j) = xVal Then
For k = 1 To UBound(rngArr, 2)
If rngArr(i, k) = Yval Then countRowAsso = countRowAsso + 1
Next k
End If
Next j
Next i
End Function
If the value is greater than or equal to 5 and less than and equal to 10 it should return the same example bellow which concatenates the Header containing the specific value in the same column:
A.S.H makes a good point on confirming that the ranges hold the same number of elements/values/cells. I've used a different approach.
Option Explicit
Public Function greaterLessValue(rng1 As Range, rng2 As Range, _
greater As Double, lesser As Double)
Dim i As Long, j As Long
Dim rngArr1 As Variant, rngArr2 As Variant
rngArr1 = rng1.Value2
rngArr2 = rng2.Value2
greaterLessValue = ""
'use for showing array extents
'delete or comment out when function works
Debug.Print LBound(rngArr1, 1) & " to " & UBound(rngArr1, 1)
Debug.Print LBound(rngArr1, 2) & " to " & UBound(rngArr1, 2)
'used to ensure that the ranges hold the same number of columns
'only affects the 2nd rank when used with Preserve
ReDim Preserve rngArr2(LBound(rngArr1, 1) To UBound(rngArr1, 1), _
LBound(rngArr1, 2) To UBound(rngArr1, 2))
For i = LBound(rngArr1, 1) To UBound(rngArr1, 1)
For j = LBound(rngArr1, 2) To UBound(rngArr1, 2)
If IsNumeric(rngArr2(i, j)) Then
If rngArr2(i, j) >= greater And rngArr2(i, j) <= lesser Then
greaterLessValue = greaterLessValue & _
IIf(CBool(Len(greaterLessValue)), ", ", vbNullString) & _
rngArr1(i, j)
End If
End If
Next j
Next i
End Function
Syntax as per the following image: