2017-04-22 50 views
0

我试图写一些VBA,将完成Excel VBA中添加新的行如果条件满足

如果行O不再是当前行明确列空,则所有数据复制到新行,然后我,J,K,L,M,N
在新插入的行明确列O

的警告我不能肯定占为-抛出一个

类型不匹配错误

这里是我试图用

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 
+0

您不能将字符串值用作布尔表达式。尝试更改'如果单元格(i,“O”)然后'为'如果不是空(单元格(i,“O”)。Value)Then' – YowE3K

+0

这将不会再抛出一个错误 - 但它将清除它的行不应该? – IcyPopTarts

+1

由于使用了“Ix:Jx:Kx:Lx:Mx:Nx:Ox + 1”的深奥范围定义 - 这实际上最终意味着范围“Ix:Ox + 1”,但它清除了错误的单元格,但不应该使用。有关该范围定义的一些有趣评论,请参阅http://stackoverflow.com/q/41653917/6535336。 – YowE3K

回答

1
从你的错误

除了工作用一个字符串作为布尔表达式的语法,有可以改变的几件事在您的代码中:

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 
+0

完美无瑕!为什么要避免使用GoTo? - 也没有使用Array()加速代码! – IcyPopTarts

+1

@IcyPopTarts - (a)'GoTo'是一个过去的宿醉,当时没有if语句。这并不是特别糟糕,如果**你在使用时要小心,但是很容易意外地在循环内部或其他不适当的地方使用GoTo,这会使代码更难调试(因为你必须向后查找代码的哪一部分跳转到标签) - 所以最好避免它。 – YowE3K

+1

@IcyPopTarts(b)如果您将信息读取到数组中,在数组中处理数组,然后将数组写回工作表,那么数组通常会加速编码,但您只能使用数组,以便可以执行UBound和LBound。 – YowE3K