首页 > 解决方案 > VBA 嵌套 FOR 循环适用于第一次出现但忽略以下循环

问题描述

我正在努力使用嵌套在另一个循环中的 FOR 循环来水平检查表的每一行,然后再移动到下一行。

目标:我需要我的代码忽略所有值为 0 的单元格,并对非零单元格进行一些基本(不相关)操作。

问题:我的代码适用于该行的第一个非零单元格,但忽略了同一行和后续行中的所有其他单元格。

代码基本结构:

我试图重新组织循环,以反转 IF Then 结构以首先忽略零单元格,但随后我找不到进入循环 2 下一次迭代的方法。

Dim RNB As Long, ROutput As Integer, VBAR As Integer, VBAC As Integer, i As Long, j As Long


'RNB        = amounts of rows to check in input table;
'ROutput    = the row number of the output table where to paste the desired values;
'VBAR       = row number of the first cell to check in the Input table;
'VBAC       = column number of the first cell to check in the Input table;
'i          = the counting variable for the vertical FOR loop; and
'j          = the counting variable for the horizontal FOR loop.

'Vertical parent FOR loop
For i = 1 To RNB
         
'Horizontal nested FOR loop: cells with a null value are ignored and the remaining ones are copied in the Output worksheet, in the first empty row available

         For j = 1 To 11
        
            If Cells(i + [2] - 1, [2] + 2 + j).Value <> 0 Then
            
                'Copy/paste of the value of the identified cell and save the row number for the remaining information to add in next steps
                [Input1].Select
                Cells(i + [VBA_Row].Value - 1, [Segment].Value + 2 + j).Copy
               
     '[Irrelevant code that actually works perfectly for the first iteration (I will display it if necessary)]

                
            Else: End If
        Next j
   Next i

没有显示错误消息。

代码执行第一次迭代的工作,但通常如果第 1 行的前 2 个单元格不等于 0:代码执行单元格 1 的工作,忽略单元格 2 并转到下一行以忽略所有其他单元格。

标签: excelvbaloopsiteration

解决方案


推荐阅读