【发布时间】:2018-12-11 21:24:41
【问题描述】:
我想要完成的是:
如果我的整个工作表中的 AC-AF 列中的任何单元格为空白,请剪切整行并粘贴到标有“MissingShipping”的新工作表中。
代码应该根据行数进行调整,因为这永远不会相同。
从我看到的示例中,我不明白在哪里插入我想要遍历的单元格范围。
我得到了错误
"对象'_Worksheet'的方法'范围'
上线NewSetup.Range(Cells(Destinationrow, 1), Cells(Destinationrow, lastcolumn)).Select。
Option Explicit
Sub Shipping()
Dim MissingShipping As Worksheet
Set MissingShipping = Sheets.Add(After:=Sheets(Sheets.Count))
MissingShipping.Name = "MissingShipping"
Dim NewSetup As Worksheet
Dim lastcolumn As Integer
Dim Destinationrow As Integer
Dim lastrow As Long
Set NewSetup = Worksheets("NKItemBuildInfoResults")
Set MissingShipping = Worksheets("MissingShipping")
Destinationrow = 1
lastcolumn = NewSetup.Range("XFD1").End(xlToLeft).Column
lastrow = NewSetup.Range("A1048576").End(xlUp).Row
Dim i As Long
Dim j As Long
For i = lastrow To 1 Step -1
For j = 1 To lastcolumn
If NewSetup.Cells(i, j).Value = "" Then
NewSetup.Activate
NewSetup.Range(Cells(i, 1), Cells(i, lastcolumn)).Cut
MissingShipping.Activate
NewSetup.Range(Cells(Destinationrow, 1), Cells(Destinationrow, _
lastcolumn)).Select
ActiveSheet.Paste
NewSetup.Rows(i).Delete shift:=xlUp
Destinationrow = Destinationrow + 1
Exit For
End If
Next j
Next i
End Sub
【问题讨论】:
-
该错误可能是由于在另一个工作表处于活动状态(在上一行激活)时尝试选择一个工作表上的单元格。如果可能,您应该尽量避免使用
.Select和Active...任何东西(即工作簿、工作表等)。例如,您可以只使用MissingShipping.Paste,而不是使用MissingShipping.Activate后跟ActiveSheet.Paste。 -
学习 VBA 的良好开端!为了帮助您进一步了解,请阅读this answer on avoiding the use of
Select。 -
感谢您的帮助!我删除了 .Select 和 .Active 但我仍然在“NewSetup.Range(Cells(i, 1), Cells(i, lastcolumn) 行上收到错误“对象'_Worksheet'的方法'范围'失败” ).Cut".. 我注意到,每当必须在两个工作表之间切换时,我总是会遇到麻烦。我是否缺少指向正确工作表的内容?
标签: arrays excel vba if-statement worksheet