简体   繁体   中英

Changing cell value using macro

I am trying to change cell values using an excel macro.

For example, changing this group:

Codes:
CareBears
Catpaws
CareBears
Catpaws
CareBears
Doghound
Catpaws
Doghound

into:

Codes:
Bear
Cat
Bear
Cat
Bear
Dog
Cat
Dog

I successfully transformed them automatically using macro recording but when the data switches position or there is an additional row of data, that data is not been read.

I am seeking your assistance regarding on this matter.

在此处输入图片说明

If you dont need to replace the values, and you only every have to deal with bears, cats and dogs you could add a formula in column B, if your codes are in column A. Its not pretty but it works.

Put this in B2, and copy down, with your codes in column A.

=IF(NOT(ISERROR(SEARCH("Bear",A2,1))),"Bear",IF(NOT(ISERROR(SEARCH("Dog",A2,1))),"Dog",IF(NOT(ISERROR(SEARCH("Cat",A2,1))),"Cat","?")))

I appreciate this doesnt answer the "macro" question. And dont try and use this if you have values like DogBear ;-)

Sub FindAndExecute()
'got the  answer working with this help http://stackoverflow.com/questions/19504858/find-all-matches-in-workbook-using-excel-vba
    Dim Sh As Worksheet
    Dim Loc As Range
    Dim Loc1 As Range
    Dim Loc2 As Range

    For Each Sh In ThisWorkbook.Worksheets
        With Sh.UsedRange
            Set Loc = .Cells.Find(What:="Carebears")
            If Not Loc Is Nothing Then
                Do Until Loc Is Nothing
                    Loc.Value = "Bear"
                    Set Loc = .FindNext(Loc)
                Loop
            End If

            Set Loc1 = .Cells.Find(What:="Catpaws")
            If Not Loc1 Is Nothing Then
                Do Until Loc1 Is Nothing
                    Loc1.Value = "Cat"
                    Set Loc1 = .FindNext(Loc1)
                Loop
            End If
            Set Loc2 = .Cells.Find(What:="Doghound")
            If Not Loc2 Is Nothing Then
                Do Until Loc2 Is Nothing
                    Loc2.Value = "Dog"
                    Set Loc2 = .FindNext(Loc2)
                Loop
            End If

        End With
        Set Loc = Nothing
        Set Loc1 = Nothing
        Set Loc2 = Nothing
    Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM