子程序填写范围内的值?

时间:2016-06-03 20:32:37

标签: excel vba excel-vba excel-2010

我一直在尝试编写一个子程序来查找一行中值的第一个和最后一个实例,并用相同的值填充中间值。但是,我无法上班。我认为问题在于我的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

2 个答案:

答案 0 :(得分:3)

通过指定.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 语句放在每个新的顶部创建代码表。这个 将避免像拼写错误那样愚蠢地编码错误以及影响你在变量中使用正确的变量类型 宣言。在没有声明的情况下即时创建的变量都是变体/对象类型。使用选项显式是 被广泛认为是“最佳实践”。

答案 1 :(得分:2)

引用你

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