我不能让我的VBA Excel宏停在行尾

时间:2014-02-04 15:55:09

标签: excel vba

我有一行数据每月更改一次,但它只更改了90个中的大约30个单元格,而且每个月它们都不同,因此我尝试制作一个宏来自动化它。

宏观察单元格A2-B98并搜索与H2-I98的值匹配的信息,如果A中的值与H匹配,则它复制I中的值并将其替换为B但是它最终停在在行的末尾,即在第98行,它无限循环。所以我希望有人能找到我的错误,以便它永远不会循环。谢谢

Sub Update_Holiday()

Dim Search As String
Dim Replacement As String
Dim rngTmp As Range
Dim rngSearch As Range

LastInputRow = Range("A65536").End(xlUp).Row
Set rngSearch = Worksheets("Holiday").Range(Cells(2, 1), Cells(98, 2))

For k = 2 to 98
    Search = Worksheets("Holiday").Cells(k, 8)
    Replacement = Worksheets("Holiday").Cells(k, 9)
    With rngSearch
        Set rngTmp = .Find(Search, LookIn:=xlValues)
        If rngTmp Is Nothing Then
            GoTo Go_to_next_input_row: 
        Else
            Worksheets("Holiday").Cells(rngTmp.Row, rngTmp.Column + 1).Value = Replacement
        End If
    End With
    Go_to_next_input_row:  
Next K

End Sub

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题:对于H2:H98中的每个Cell,你正在寻找A2:A98中的匹配。它不一定在同一行。如果在列A中找到匹配项,则需要从列B中获取值并将其放在与我们刚查找的搜索值相同的行中的列I中。在这种情况下,此代码将起作用:

Option Explicit
Sub Test()

Dim ws          As Worksheet
Dim srcRng      As Range        '' Source range
Dim schRng      As Range        '' Search range
Dim c           As Range
Dim search      As Range

Set ws = ThisWorkbook.Sheets(1)
Set srcRng = ws.Range("H2:H98")
Set schRng = ws.Range("A2:A98")

For Each c In srcRng     '' Iterate through your source range
    Set search = schRng.Find(c.Value, LookIn:=xlValues, SearchDirection:=xlNext)     '' Find the value from column H in column A
    If Not search Is Nothing Then
        c.Offset(, 1).Copy search.Offset(, 1)   '' Get the value from column B, from the same row as the value it found in column A
                                                '' Then paste that value in column I, on the same row as the value we searched for from column H
    End If
Next c

GoTo语句通常(通常,并非总是)非常非常不良做法。特别是在这种情况下。你不需要它们,只会让你的代码变得错综复杂。