我一直在尝试编写一个子例程来查找连续值的第一个和最后一个实例,并用相同的值填充中间。但是,我上类有困难。我认为问题在于我的 range.find 方法来查找最后一个实例。有人可以帮我找出错误吗?
Sub ChangeBetween()
Dim FirstCell As Range
Dim LastCell As Range
Dim SearchTerm As String
Dim ChangeRange As Range
Dim ChangeCell As Range
'Define search term
SearchTerm = Range("A1").Value
'Find beginning and end of replacement range
Set FirstCell = Range("B2:I2").Find( _
What:=SearchTerm, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext)
Set LastCell = Range("B2:I2").Find( _
What:=SeartTerm, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious)
'Set replacement range
Set ChangeRange = Range(FirstCell, LastCell)
'Replace in range
For Each ChangeCell In ChangeRange
ChangeCell.Value = SearchTerm
Next ChangeCell
End Sub
最佳答案
通过指定 .Find method 的 After:= 参数,我发现了几个(我认为是)逻辑漏洞。 .
Option Explicit 'see footnote ¹
Sub ChangeBetween()
Dim firstCell As Range, lastCell As Range, searchTerm As String
With Worksheets("Sheet3")
'Define search term
searchTerm = .Range("A1").Value
'Find beginning and end of replacement range
With .Range("B2:I2")
'make sure there is at least one SearchTerm
If CBool(Application.CountIf(.Cells, searchTerm)) Then
Set firstCell = .Find(What:=searchTerm, _
After:=.Cells(.Columns.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext)
Set lastCell = .Find(What:=searchTerm, _
After:=.Cells(1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious)
.Parent.Range(firstCell, lastCell) = searchTerm
End If
End With
End With
End Sub
¹ 设置 需要变量声明 在 VBE 的工具 ► 选项 ► 编辑器属性页中将放置 Option Explicit 每个新创建的代码表顶部的语句。这个
将避免愚蠢的编码错误,如拼写错误,并影响您在变量中使用正确的变量类型
宣言。动态创建的没有声明的变量都是变体/对象类型。使用 选项显式 是
被广泛认为是“最佳实践”。
关于vba - 子程序填写范围内的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622905/