2017-04-22 45 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