Search code examples
excelvbafind-replace

Excel VBA find and replace from a table on difference worksheet


I am working on a project that will filter our SC sales taxes by tax codes. In order to do this, I have to write some codes to get things corrected e.g. the city names. Seeing that sometimes this information is manually put into our system, the spellings can vary causing my codes to not work properly. So, I have created a new worksheet "CITY FIND REPLACE" where there is a "find" column(A) of incorrect spellings and a "replace" column (B) with the way it needs to be so that my codes work correctly. I need it in a table so that each month I do it and find more/different spellings of the cities, I can add them to the search list so that it will catch and change them.

I am having a hard time getting the code I have found to pull from a different worksheet and I am not sure what I am doing wrong. I want it to search through Column H on Sheet1 (RAW DATA) (the # of rows can change each month as well so I just need it to go through the bottom of the data but that can't be a set #) and then compare each cell to Sheet12 (CITY FIND REPLACE) TABLE 1 column A. If they match, change it to Sheet12 (CITY FIND REPLACE) column B.

Note: VBA coding is not my thing. I fumbled through and used stackoverflow to help me on another project and now my work thinks I am good at this... and I am not. I don't understand it. Any help in plain English would be amazing.

Sub FindReplace()

    For i = 2 To 40
        Worksheets("RAW DATA").Range("H:H").Select
        Selection.Replace what:=Worksheets("CITY FIND REPLACE").Cells(i, 1).Value,
        replacement:=Worksheets("CITY FIND REPLACE").Cells(i, 2).Value, lookat:=xlPart,
        searchorder:=xlByRows, MatchCase:=False

    Next

    Worksheets("RAW DATA").Cells(1, 1).Select

End Sub

I am right now getting

RUN TIME ERROR'1004': SELECT METHOD OF RANGE CLASS FAILED.

When I click debug it will highlight the line Worksheets("RAW DATA").Range("H:H").Select.


Solution

  • I can't see any reason why this wouldn't work.

    Sub FindReplace()
    
    For i = 2 To 40
        Worksheets("RAW DATA").Range("H:H").Replace what:=Worksheets("CITY FIND REPLACE").Cells(i, 1).Value, _
                                       replacement:=Worksheets("CITY FIND REPLACE").Cells(i, 2).Value, lookat:=xlPart, _
                                        searchorder:=xlByRows, MatchCase:=False
    Next i
    
    End Sub