mardi 22 septembre 2020

Using Match function in a nested For loop to find the closest value VBA

I have a table of data with 30 rows and 14 columns. The data is organized in ascending order. The goal of the function being created is to search through each cell to find the specific Car the user has entered. Then search the column of the Car to find the distance it can travel.Then from finding the distance row, move over to the oil column to get the value as the output. The problem I am facing is how to have the search be similar to the match function where it can find the closest value (lower in my case) while running the loop.

This is what I have prior to trying to add a match function:

Function findoil(car As String, distance As String, condition As String) As String

Dim row As Integer
Dim column As Integer
Dim temp As Integer
Dim Target As Integer
Dim oil_col As Integer
Dim sheet_tab As String


For row = 1 To 100

    For column = 1 To 100
    
        If Worksheets(sheet_tab).Cells(row, column).Value = car Then
        
            For temp = 1 To 100
            
                If Worksheets(sheet_tab).Cells(temp, column).Value = distance Then
                
                For oil_col = 1 To 100
                    
                    If Worksheets(sheet_tab).Cells(row, oil_col).Value = "oil" Then
                        findoil = Worksheets(sheet_tab).Cells(temp, oil_col)
                    End If
                    
                    Next oil_col            
                End If
            Next temp
        End If
    Next column
Next row

End Function

Using this function I can only find the value if it is exact. I would like to be able to find the closest cell in the column to the inputted value.

Aucun commentaire:

Enregistrer un commentaire