如果找到单词,则更改列中的所有单元格

时间:2014-09-15 07:57:09

标签: excel excel-vba vba

我有一个包含6列的工作表,我希望匹配E列中的某个单词,如果它在该列的任何单元格中,则用该单词替换整个列。

Sub Macro8()
    Columns("E:E").Select
    If Columns("E:E").Select = "dog" Then Entire.Columns("E:E").Select = "dog"
End Sub

1 个答案:

答案 0 :(得分:1)

就像我在上面的评论中提到的那样,使用Worksheet_Change事件。但是,如果您想在方便时运行例程,请使用此代码

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find Lastrow in Col E which has data
        lRow = .Range("E" & .Rows.Count).End(xlUp).Row

        '~~> Use Countif to check for an occurance of Dog in Col E
        If Application.WorksheetFunction.CountIf(.Columns(5), "Dog") _
        Then .Range("E1:E" & lRow).Value = "Dog"
    End With
End Sub