使用宏更改单元格值

时间:2016-05-05 10:18:38

标签: excel vba excel-vba

我正在尝试使用excel宏更改单元格值。

例如,更改此组:

Codes:
CareBears
Catpaws
CareBears
Catpaws
CareBears
Doghound
Catpaws
Doghound

成:

Codes:
Bear
Cat
Bear
Cat
Bear
Dog
Cat
Dog

我使用宏录制成功地自动转换了它们,但是当数据切换位置或者有一行额外的数据时,该数据未被读取。

我正就此事寻求你的协助。

2 个答案:

答案 0 :(得分:0)

enter image description here

如果您不需要更换值,并且您只需要处理熊,猫和狗,您可以在B列中添加公式,如果您的代码在A列中。它不漂亮但它有效。< / p>

将其放入B2中,然后将您的代码复制到A列。

  

= IF(NOT(ISERROR(SEARCH(&#34;熊&#34;,A2,1))),&#34;熊&#34;,IF(NOT(ISERROR(SEARCH(&#34;狗& #34;,A2,1))),&#34;狗&#34;,IF(NOT(ISERROR(SEARCH(&#34;目录&#34;,A2,1))),&#34;目录&# 34;,&#34;&#34;)))

我很欣赏这不会回答&#34;宏&#34;题。如果你有像DogBear这样的值,请不要尝试使用它; - )

答案 1 :(得分:0)

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