VBA-尝试遍历所有行时跳过行

时间:2018-11-15 01:09:00

标签: excel vba

我正在尝试编写代码,该代码将遍历电子表格中每个选项卡的每一行,并且如果W和X列中的值大于0,请将该行写入称为“预算”的选项卡中的下一个可用行在同一电子表格中。当我运行它时,它跳过每隔一行。任何意见,将不胜感激。我认为这与所选范围有关,并且与相对于行有关,但是我无法弄清楚如何正确设置上下文。

Sub Button1_Click()

Dim source As Worksheet
Dim target As Worksheet
Dim targetLastRow As Long
Dim LastRow As Long

Set target = ThisWorkbook.Sheets("Budget")
targetLastRow = target.Range("A" & target.Rows.Count).End(xlUp).Row

    For Each ws In Worksheets
        Set source = ws     
        'do not read rows from budget because that is our target
        If source.Name <> "Budget" Then 
            'get the last row in the current sheet
            LastRow = source.Cells(source.Rows.Count, "X").End(xlUp).Row

            Set rowRange = source.Range("A1:A" & LastRow)

            'Loop through each row
            For Each r In rowRange            
                'if column W and X have valuces then write the row to the target sheet
                If source.Cells(r.Row, 24) > 0 And source.Cells(r.Row, 23) > 0 Then      
                    target.Cells(targetLastRow, 1) = source.Cells(r.Row, 23)
                    'activeRow.EntireRow.Copy target.Cells(1, targetLastRow)
                    targetLastRow = targetLastRow + 1

                End If
            Next r

            MsgBox ("Processing complete for Sheet: " & source.Name)
        End If
    Next ws
End Sub

1 个答案:

答案 0 :(得分:0)

尝试一下:

ans =
     1     1
     3     1