2017-07-28 175 views
0
Sub compareLines() 

    Application.ScreenUpdating = False 
    ActiveSheet.Cells(3, 3).Activate 

    While ActiveCell.Value <> "" 

     If ActiveCell.Value - ActiveCell.Offset(-1, 0).Value < 0 Then 

      ActiveCell.EntireRow.Delete 

     Else 

      ActiveCell.Offset(1, 0).Activate 

     End If 

    Wend 

    Application.ScreenUpdating = True 

    End Sub 

這是我的代碼,我目前的錯誤。Excel VBA運行時錯誤'13'類型不匹配

錯誤是Excel VBA runtime error "13 type mismatch

線的錯誤是:If ActiveCell.Value - ActiveCell.Offset(-1, 0).Value < 0 Then

此代碼已在以前的工作表的工作,但是當我輸入這個宏到一個新的工作表,它似乎並沒有工作。我在SO上找到的所有解決方案似乎都不適用於我的情況,因此對此問題的任何幫助將不勝感激。

我使用的數據樣本:
enter image description here

+0

哪一行會引發錯誤?此外,我會建議你在模塊中有這個,並根據需要拋出工作表 – Zac

+0

@Zac'如果ActiveCell.Value - ActiveCell.Offset(-1,0).Value <0 Then# –

+0

什麼是「ActiveCell.Value」和「ActiveCell.Offset(-1,0).Value」的值? – braX

回答

1

一般來說,On Error Resume Next的東西,你應該與非常小心。

如果你把它放在你的代碼中,它會開始忽略錯誤,並且如果有人在你之後使用代碼,他根本不會高興(或者他會認爲你是一個業餘或工作防禦者)。話雖如此,CPearson有一篇關於它的好文章,值得一讀 - http://www.cpearson.com/excel/errorhandling.htm

最後但並非最不重要的一點,確保您將On Error Resume Next更改爲其他內容,一旦您意識到錯誤發生的原因。

對於您的情況,使用IsNumeric函數來避免TypeMismatch錯誤是個好主意。如果出現其他錯誤,請儘量避免使用類似的問題。

Dim v1 as Range, v2 as Range 
While ActiveCell.Value <> "" 
    Set v1 = ActiveCell.Value 
    Set v2 = ActiveCell.Offset(-1) 
    If IsNumeric(v1) And IsNumeric(v2) Then 
     'Both are numeric, so it's safe to perform arithmetic against these values 
     If v1 - v2 < 0 Then 
      ActiveCell.EntireRow.Delete 
     Else 
      ActiveCell.Offset(1, 0).Activate 
     End If 
    Else: ActiveCell.Offset(1, 0).Activate 
    End If 
Wend 
相關問題