简体   繁体   English

Excel VBA-For循环。使用值查找单元格

[英]Excel VBA - For loop .Find cell with value

I am struggling to write an effective macro that will find a cell with error in column, then replace that cell with value of the first non-empty cell without error below it (there might be consecutive error cells) then loop for 12 columns. 我正在努力编写一个有效的宏,该宏将在列中找到一个有错误的单元格,然后将该单元格替换为第一个非空单元格的值,而该单元格下面没有错误(可能有连续的错误单元格),然后循环12列。

The code I have below replaces each of the error cells in all 12 columns, but not in a consistent manner: some cells will indeed be filled by the next cell below that contains a number, but some cells end up with value of the second next cell below that contains a number. 我下面的代码替换了所有12列中的每个错误单元格,但不是以一致的方式进行替换:某些单元格的确会被下面包含数字的下一个单元格填充,但是某些单元格的值以第二个next值结尾下方的单元格包含一个数字。 I can't tell where the problem in my code is. 我无法确定代码中的问题在哪里。

Option Explicit
Sub ClearError()

    ThisWorkbook.Sheets("WorkSheet1").Activate

    Dim c, x, z As Integer
    Dim y As Long

    For z = 3 To 14 Step 1   ' Start with column 'C' and do for total of 12 columns
    x = 999

        For c = 1 To x Step 1
            If IsError(Cells(c, z)) Then
               Cells(c, z) = Range(Cells(1, z), Cells(x, z)).Find(y, _
                             After:=Cells(c, z), LookIn:=xlValues, SearchDirection:=xlNext).Value
            End If
        Next c   
    Next z

End Sub

If you could offer any insight or advice, I would greatly appreciate it. 如果您能提供任何见解或建议,我将不胜感激。 Thank you for your time! 感谢您的时间! Ante 赌注

Try reversing your loop. 尝试反转循环。

For c = x to 1 Step -1
    If IsError(Cells(c, z)) Then
           Cells(c, z) = Cells(c + 1, z)
    End If
Next c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM