引数を受け取り、指定された条件に一致するレコードを抽出するVBA関数の例

Function searchArray(arr As Variant, val1 As Variant, val2 As Variant, col1 As Long, col2 As Long) As Variant()
Dim numRows As Long
numRows = UBound(arr, 1)

Dim result() As Variant
Dim resultCount As Long
ReDim result(1 To numRows, 1 To UBound(arr, 2))

Dim i As Long
For i = 1 To numRows
    If arr(i, col1) = val1 And arr(i, col2) = val2 Then
        resultCount = resultCount + 1
        Dim j As Long
        For j = 1 To UBound(arr, 2)
            result(resultCount, j) = arr(i, j)
        Next j
    End If
Next i

If resultCount > 0 Then
    ReDim Preserve result(1 To resultCount, 1 To UBound(arr, 2))
Else
    ReDim result(1 To 1, 1 To UBound(arr, 2))
End If

searchArray = result

End Function

コメント

タイトルとURLをコピーしました