在循环中跳过单行代码:entirerow.delete 在另一个工作簿中

Skipping single line of code in loop: entirerow.delete in another workbook

对 VBA 相当陌生,但我正在尝试将所选工作簿中的 (copy/paste) 数据导入我的主工作簿(保留代码),但首先需要删除不可用的行选定的工作簿。

如果 C 列为空,那么在将数据复制到我的主工作簿之前,我想使用从下到上的循环删除整行(因此需要更明确地引用每个 wb)。

它目前在我的循环中跳过了 "wb.Sheets(1).Rows(r).EntireRow.Delete" 行代码,但执行了正确的循环次数。请帮忙,还在学习中。

早些时候,它错误地删除了每一行:当我的 if then 子句引用了一个不同的单元格(一个有值,而不是空白的单元格)。

Dim wb As Workbook
Dim r As Integer

With wb.Sheets(1)       
     For r = wb.Sheets(1).UsedRange.Rows.Count To 1 Step -1
         If wb.Sheets(1).Cells(r, "C") = "0" Then
             wb.Sheets(1).Rows(r).EntireRow.Delete 
         End If
     Next

像这样的东西应该有用。您已经为代码使用了 With 块,但实际上并没有使用它。您不需要对同一对象的其他引用。在此我测试了单元格是否为空未使用 IsEmpty

Dim wb As Workbook
Dim r As Integer

With wb.Sheets(1)
    For r = .UsedRange.Rows.Count To 1 Step -1
        If IsEmpty(.Cells(r, 3)) Then
            .Rows(r).Delete
        End If
    Next
End With

删除行(标准列)

联盟版

Sub DelRows()

    Const cSheet As Variant = 1     ' Worksheet Name/Index
    Const cFirst As Long = 1        ' First Row Number
    Const cColumn As Variant = "C"  ' Criteria Column Letter/Number

    Dim rngU As Range   ' Union Range
    Dim LastUR As Long  ' Last Used Row
    Dim r As Long       ' Row Counter

    With ThisWorkbook.Worksheets(cSheet)

        ' Check if worksheet is empty.
        If .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), -4123, , 1) _
                Is Nothing Then Exit Sub
        ' Calculate Last Used Row.
        LastUR = .Cells.Find("*", , , , , 2).Row

        ' Add found criteria first (can be any) column cells to Union Range.
        For r = cFirst To LastUR ' Rows
             If IsEmpty(.Cells(r, cColumn)) Then
                 If Not rngU Is Nothing Then
                     Set rngU = Union(rngU, .Cells(r, 1))
                   Else
                     Set rngU = .Cells(r, 1)
                 End If
             End If
        Next

    End With

    ' Delete rows in one go.
    If Not rngU Is Nothing Then
        rngU.EntireRow.Delete ' .Hidden = True
        Set rngU = Nothing
    End If

End Sub