rluth
rluth

Reputation: 41

Search program in VBA

I am coding a search that traverses a dataset on an excel worksheet. Currently the code runs for an exact match, matching the search field with the cell. However, I want my program to be able to search and give results even with instances of the search in the cell (string within the cell). For example, search for the word "dog" in the cell which has "this dog is brown" should return the entire cell.

Ive already tried the following incorporating the following piece, but it doesnt work

searchString = dataArray(i, searchField)
If InStr(UCase("searchString"), UCase("searchField")) = 1 Then

The following is the actual code:

'Get the range values into a variable that can be looped through.

'Example usage: dataArray(1,1) [row,column]

'Simple version: ws.Range(Cells(1,1),Cells(2,2)).Value

dataArray = ws.Range(ws.Cells(dataRowStart, dataColumnStart), ws.Cells(ws.Cells(Rows.Count, dataColumnStart).End(xlUp).Row, dataColumnEnd)).Value

        'Increase size of array that will hold the data to display to its max possible size for the current worksheet.
        ReDim datatoShowArray(1 To UBound(dataArray, 1), 1 To UBound(dataArray, 2))

        'Row increment for the final data array (datatoShowArray).
        j = 1

        'Loop through the rows in the data range.
        For i = 1 To UBound(dataArray, 1)

            'Check if the value in the row equals our search value
            If (dataArray(i, searchField) = searchValue) Then


                'MATCH FOUND! Now do something!

                'Loop through the columns in the data range so can get their values.
                For k = 1 To UBound(dataArray, 2)

                    'Add values to the array that will be used to put data into the Dashboard.
                    datatoShowArray(j, k) = dataArray(i, k)

                Next k

                'Increment the counter for the datatoShowArray
                j = j + 1


            End If

Upvotes: 0

Views: 66

Answers (1)

Tyler Edwards
Tyler Edwards

Reputation: 184

Remove the quotes from If InStr(UCase("searchString"), UCase("searchField")) = 1 Then, currently it is using those values as strings, or text literals, but you want them to reference the actual variables:

If InStr(UCase(searchString), UCase(searchField)) >= 1 Then

Upvotes: 1

Related Questions