VBA范围select

如果find某个文本,我使用此脚本清除相邻单元格的内容。 然而,我不知道如何改变从当前区域严格列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 

循环遍历给定范围的所有单元可能会耗费大量时间

你可以使用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 

尝试像这样将search范围限制在列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