Home » excel » excel – Issue using Instr with Cell Formats

excel – Issue using Instr with Cell Formats

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a puzzle that i’ve trying to solve for some time. I have a spreadsheet that imports data from a .csv file, which worls well apart from the intial location setting.

I currently run a search to find the last cell that contains a value and use that as the starting point. Now for reason above and beyond me this sometimes fails and places the starting point halfway down the spreadsheet. SO to get around this I decided to write a check code or a more sophisticated location finder.

The new Location finder is as follows

    For a = 1 To 400

    Dim SearchString As Variant
    Dim SearchSymbol As String

    SearchString = Cells(NewLastRowNumber, 10)
    SearchSymbol = "€"

        If InStr(1, SearchString, SearchSymbol, 1) = 0 Then

            NewLastRowNumber = NewLastRowNumber - 1

        Else

            NewLastRowNumber = NewLastRowNumber + 1
            Exit For
        End If

Next a

This works, apart from the what it searches within the cell. The ideal behind is it search a column of data containing cost, i.e (Row 1 -> €100, Row 2 -> €235 etc..) and find the last cell containng currently I can only ever get it to find the column header and not the cell.

Each cell in the column is formatted as a Custom (€0.00), not sure if this makes any difference or not.

Ive embeded some images to further demonstrate my issue.

Copy of sample spreadsheet

Image of code describing cell value
At this point NewLastRowNumber = 13

At this point the loop should break and record NewLastRowNumber = 13 but instead it continues until it finds the column header.

Hope this all makes sense & thanks.

How to&Answers:

The cell is formatted as Currency or Custom, thus you cannot find the Euro sign there. When you check InStr(), it checks the cell .Value, not the .Format.

To find the Eur in the Cell, check the format like this:

If Cells(NewLastRowNumber, 10).NumberFormat = "€0.00" Then

To see the exact number format in VBA, select the cell with the wanted format and run the following:

Sub Test()
    Debug.Print Selection.NumberFormat
End Sub