子程序来填写范围内的值?

我一直在试图编写一个子程序来查找一行中第一个和最后一个值的实例,并用相同的值填充中间值。 但是,我很难开始工作。 我认为问题是用我的range.find方法来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方法的After:=参数,我select了一些(我认为是)逻辑漏洞。

 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工具中设置需要variables声明 ►选项►编辑器属性页面将把Option Explicit语句放在每个新创build的代码表的顶部。 这将避免像拼写错误这样的愚蠢的编码错误,也会影响你在variables声明中使用正确的variablestypes。 在没有声明的情况下即时创build的variables都是变体/对象types。 使用Option Explicit被广泛认为是“最佳实践”。

引用你

 Set LastCell = Range("B2:I2").Find( _ What:=SeartTerm, _ 'this is a typo your variable is SearchTerm LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious) 

如果可以的话,为什么要从最后和最先循环到每个细胞?

 'Replace in range For Each ChangeCell In ChangeRange ChangeCell.Value = SearchTerm Next ChangeCell 

尝试:

 ChangeRange.Value = SearchTerm