要求:
找到包含单词TOTAL 的单元格,然后在其下方的单元格中输入破折号。
解决方案:
此解决方案使用Range 对象的Find 方法,因为使用它而不是蛮力(For…Next 循环)似乎合适。
该方法的解释和详细信息见Range.Find method (Excel)
实施:
为了提供灵活性,Find 方法被包装在这个函数中:
Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean
其中:
sWhat:包含要搜索的string
rTrg:是要搜索的range
如果找到任何匹配,该函数返回True,否则返回False
此外,每次函数找到匹配项时,它都会将生成的range 传递给过程Range_Find_Action 以执行所需的操作,(即“在其下方的单元格中输入破折号” )。 “必需的操作”位于一个单独的过程中,以允许自定义和灵活性。
这是函数的调用方式:
此测试正在搜索“total”以显示MatchCase:=False 的效果。通过将匹配更改为MatchCase:=True
,可以使匹配区分大小写
Sub Range_Find_Action_TEST()
Dim sWhat As String, rTrg As Range
Dim sMsgbdy As String
sWhat = "total" 'String to search for (update as required)
Rem Set rTrg = ThisWorkbook.Worksheets("Sht(0)").UsedRange 'Range to Search (use this to search all used cells)
Set rTrg = ThisWorkbook.Worksheets("Sht(0)").Rows(6) 'Range to Search (update as required)
sMsgbdy = IIf(Range_ƒFind_Action(sWhat, rTrg), _
"Cells found were updated successfully", _
"No cells were found.")
MsgBox sMsgbdy, vbInformation, "Range_ƒFind_Action"
End Sub
这是查找功能
Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean
Dim rCll As Range, s1st As String
With rTrg
Rem Set First Cell Found
Set rCll = .Find(What:=sWhat, After:=.Cells(1), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Rem Validate First Cell
If rCll Is Nothing Then Exit Function
s1st = rCll.Address
Rem Perform Action
Call Range_Find_Action(rCll)
Do
Rem Find Other Cells
Set rCll = .FindNext(After:=rCll)
Rem Validate Cell vs 1st Cell
If rCll.Address <> s1st Then Call Range_Find_Action(rCll)
Loop Until rCll.Address = s1st
End With
Rem Set Results
Range_ƒFind_Action = True
End Function
这是动作过程
Sub Range_Find_Action(rCll)
rCll.Offset(1).Value2 = Chr(167) 'Update as required - Using `§` instead of "-" for visibilty purposes
End Sub