VBA范围选择

时间:2017-01-03 17:19:49

标签: excel vba excel-vba

如果找到某个文本,我使用此脚本清除相邻单元格的内容。但是,我不知道如何将范围从当前区域更改为严格的A列到T.我尝试了ActiveSheet.Range("A:T").Select但是没有用。

任何帮助将不胜感激。这是代码:

Sub Clear_Text()
    Dim rng1 As Range
    Dim rng2 As Range
    Set rng1 = ActiveSheet.Range("A1").CurrentRegion

    For Each rng2 In rng1
        If rng2 Like "Error" Or _
        rng2 Like "Mistake" Then rng2.Offset(, 1).ClearContents
    Next
End Sub

2 个答案:

答案 0 :(得分:3)

循环遍历给定范围的所有单元格可能非常耗时

您可以使用Find()功能仅跳转到相关的单元格:

Option Explicit

Sub Clear_Text()
    With Range("T1", Cells(Rows.Count, "A").End(xlUp))
        CheckAndClear .Cells, "Error"
        CheckAndClear .Cells, "Mistake"
    End With
End Sub

Sub CheckAndClear(rng As Range, strng As String)
    Dim f As Range
    Dim firstAddress As String

    With rng
        Set f = .Find(what:=strng, LookIn:=xlValues, lookat:=xlPart) '<--|with 'lookat:=xlPart' parameter specification makes you catch cell that contains the searched string
        If Not f Is Nothing Then
            firstAddress = f.Address
            Do
                f.Offset(, 1).ClearContents
                Set f = .FindNext(f)
            Loop While f.Address <> firstAddress
        End If
    End With
End Sub

答案 1 :(得分:1)

像这样尝试将搜索范围限制为A:T列:

Sub Clear_Text()
    Dim cl As Range

    For Each cl In ActiveSheet.Range("A1:T" & Range("A1").CurrentRegion.Rows.Count)
        If cl Like "Error" Or cl Like "Mistake" Then
            cl.Offset(0, 1).ClearContents
        End If
    Next
End Sub
相关问题