我不确定是因为我使用的是 mac 还是代码错误,但是行没有正确识别,因此没有将其删除或粘贴到另一个电子表格中。我必须运行代码三遍才能正确地通过它并将单元格复制/粘贴并删除到另一个电子表格中。
非常感谢!
这是代码:
Dim j, lastidno As Long
Sheets("Part B + C Modules").Activate
lastidno = Range("A2", Range("A2").End(xlDown)).Count + 1
For j = 2 To lastidno
If Range("O" & j) = "" Then
Sheets("Part B + C Modules").Range("A" & j).Copy
Sheets("No Options Selected").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("Part B + C Modules").Activate
Rows(j).EntireRow.Delete
End If
Next
MsgBox "done"
End Sub
最佳答案
使用负数 Step
向后迭代和删除行> For j = lastidno to 2 Step -1
但是,您似乎可以更优雅地重写代码以避免:
Range
引用资料 Activate
或 Select
关键是要有
Explicit
工作表引用。也可以使用SpecialCells
可以在这里派上用场返回 Range
一口气(所以不再重复)。这样您也可以一次性删除所有行!例如,您的代码可能如下所示:
Sub Test()
'Set up your worksheet variables
Dim ws1 As Worksheet: Set ws1 = Worksheets("Part B + C Modules")
Dim ws2 As Worksheet: Set ws2 = Worksheets("No Options Selected")
'Get last used rows
Dim lr1 As Long: lr1 = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row
Dim lr2 As Long: lr2 = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row
'Set your range and copy it
Dim rng As Range: Set rng = ws1.Range("O2:O" & lr1).SpecialCells(xlCellTypeBlanks).Offset(0, -14)
rng.Copy ws2.Cells(lr2 + 1, 1)
'Delete your range
rng.EntireRow.Delete
MsgBox "done"
End Sub
小渔获:
SpecialCells
当没有找到空单元格时将返回错误。您可能想使用 On error
来解决这个问题。或计算 Range
中的空单元格首先(我个人的喜好)。因此,该特定部分可能如下所示:'Set your range and copy it
If WorksheetFunction.CountBlank(ws1.Range("O2:O" & lr1)) > 0 Then
Dim rng As Range: Set rng = ws1.Range("O2:O" & lr1).SpecialCells(xlCellTypeBlanks).Offset(0, -14)
rng.Copy ws2.Cells(lr2 + 1, 1)
End If
另一个小笔记供将来引用:
Dim j, lastidno As Long
只有 lastidno
声明为 Long
数据类型。 j
变量自动分配给 Variant/Integer
因此,当您的数据大于此数据类型可以容纳的数据时,可能会成为问题 > 返回 OverFlow
错误。
关于excel - 我必须多次运行我的代码才能完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59608715/