[英]Type mismatch runtime error (13) for vba
我想對該區域進行過濾並刪除與該區域不匹配的其余行。 工作表中沒有公式,只有值和字符。 這是我正在處理的較大代碼的一部分,所以我只發布這部分,這是我第一次看到錯誤,所以對於其他工作表,它們按照我聲明的方式工作得很好。
有錯誤不會通過的行在這里If InStr(1, Rng10.Cells(q, 1).Value, "NW") = 0 Then
我的數據有一個輔助列,它是 W,我正在過濾它。 我確保我使用的變量沒有重復。 (我使用過 s、t、m、n 等...)我試圖將 q 聲明為 double 或 variate,但它們都不起作用。
sub test()
Worksheets("A").Activate
'filter
Dim sh9 As Worksheet
Set sh9 = Sheets("A")
Dim LR16 As Long
Dim Rng10 As Range
Dim q As Long
LR16 = sh9.Cells(Rows.Count, "B").End(xlUp).Row
Set Rng10 = Range("W5:W" & LR16 - 1)
For q = Rng10.Rows.Count To 1 Step -1
If InStr(1, Rng10.Cells(q, 1).Value, "NW") = 0 Then
Rng10.Cells(q, 1).EntireRow.Delete
End If
Next q
end sub
If InStr(1, Rng10.Cells(q, 1).Value, "NW") = 0 Then
您假設Rng10.Cells(q, 1).Value
的類型是什么,並且您假設無論該類型是什么,VBA 都可以將其隱式轉換為String
以傳遞給InStr
函數。
當單元格包含錯誤值( #N/A
、 #VALUE!
、 #REF!
或任何其他錯誤)時, thatCell.Value
的類型為Error
- VBA 不知道如何將Error
值轉換為String
值(或其他任何事情),因此它會引發運行時錯誤 13類型不匹配,並迫使您改為修復代碼。
您可以使用IsError
函數檢查單元格的值是否為Error
:
Dim myValue As Variant
myValue = Rng10.Cells(q, 1).Value
If IsError(myValue) Then
'cell contains an error
Else
'cell contains no error: myValue is safe to convert to a string
If InStr(1, CStr(myValue), "NW") = 0 Then
'...
End If
End If
旁注,注意適當的縮進如何使代碼更容易理解。
不要使用.Value
,使用.Text
將錯誤視為文本等價物。
改變
If InStr(1, Rng10.Cells(q, 1).Value, "NW") = 0 Then
至
If InStr(1, Rng10.Cells(q, 1).Text, "NW") = 0 Then
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.