如果条件满足,Excel VBA添加新行

我正在尝试写一些将完成的VBA

如果行O不为空,则将所有数据复制到新行,然后在当前行中清除列I,J,K,L,M,N
在新插入的行中清除O列

我不能解释的警告是-抛出一个

types不匹配错误

这是我正在尝试使用的语法

 Sub BlueBell() Application.ScreenUpdating = False Dim i As Long, y ReDim y(2 To Range("A" & Rows.Count).End(3).Row) For i = UBound(y) To LBound(y) Step -1 If Cells(i, "O") Then If Cells(i, "I") = "" And Cells(i, "K") = "" And Cells(i, "M") = "" Then GoTo DoNothing Else Rows(i).Copy Cells(i, "A").Insert Range("I" & i & ":J" & i & ":K" & i & ":L" & i & ":M" & i & ":N" & i & ":O" & i + 1).ClearContents GoTo DoNothing End If End If DoNothing: Next i End Sub 

除了使用string作为布尔expression式的错误,还有几件事情可以在你的代码中改变:

 Sub BlueBell() Application.ScreenUpdating = False Dim i As Long ', y() As Variant 'ReDim y(2 To Range("A" & Rows.Count).End(3).Row) 'Why use an array? For i = Range("A" & Rows.Count).End(3).Row To 2 Step -1 If Not IsEmpty(Cells(i, "O").Value) Then 'Avoid the use of GoTo If Cells(i, "I").Value <> "" Or _ Cells(i, "K").Value <> "" Or _ Cells(i, "M").Value <> "" Then Rows(i).Copy Cells(i, "A").Insert 'Don't use a "Ix:Jx:Kx:Lx:Mx:Nx:Ox+1" range - it will lead to problems 'because even really experienced users don't understand what it does Range("I" & i & ":N" & i).ClearContents Range("O" & i + 1).ClearContents End If End If Next i 'It's a good habit to reset anything that you disabled at the start of your code Application.ScreenUpdating = True End Sub