赶上Vlookup 1004错误

我试图使用Vlookup在“数据库”(DB_SHEET)中查找一些税款。 当我的名字不存在于我的数据库中时,我在VlookUp中得到错误“1004”。

为什么“错误转到Err1”没有捕获错误?

我的代码:

Dim tax1 as Double, tax2 as Double, name as String On Error GoTo Err1 While Cells(rowIndex, 1) <> "" name = Cells(rowIndex, 4) fin = Cells(rowIndex, 5) * Cells(rowIndex, 6) tax1 = WorksheetFunction.VLookup(name, Sheets(DB_SHEET).Range("D:G"), 3, False) tax2 = WorksheetFunction.VLookup(name, Sheets(DB_SHEET).Range("K:P"), 2, False) Cells(rowIndex, 8) = (fin * tax1) - (fin * tax2) Err1: rowIndex = rowIndex + 1 Wend On Error Goto 0 

我已经知道一个可行的代码,但我想明白为什么我不能做“WorksheetFunction”,并使用“错误”捕获错误。

其他版本的作品:

 Dim tax1 as Variant, tax2 as Variant, name as String While Cells(rowIndex, 1) <> "" name = Cells(rowIndex, 4) fin = Cells(rowIndex, 5) * Cells(rowIndex, 6) tax1 = WorksheetFunction.VLookup(name, Sheets(DB_SHEET).Range("D:G"), 3, False) tax2 = WorksheetFunction.VLookup(name, Sheets(DB_SHEET).Range("K:P"), 2, False) If Not IsError(tax1) And not IsError(tax2) Then Cells(rowIndex, 8) = (fin * tax1) - (fin * tax2) End if rowIndex = rowIndex + 1 Wend 

编辑(之后:K_B回答)

1)如果我使用Application.Vlookup(…)insead的WorksheetFunction.Vlookup(…)我得到“错误13”。

这是因为Excel错误和VB错误的区别。 你的VLookup投了一个Excel错误,但VB代码工作正常(该变种现在只包含错误代码)。 如果你想在你的VBA中做1/0,你会得到一个VB错误,这个错误将被On Error GoTo ...捕获On Error GoTo ...

你已经find了自己的解决scheme,通过检查expression式的值是否与IsError()函数的错误来捕获Excel错误,所以我不能把你填在那里!

现在假设tax1tax2是十进制数,通常你可以改变这两个variables的Dim以反映这一点,并把它们定义为Single而不是Variant 。 现在你会得到一个VB错误,当你的VLookup失败,因为错误不能放在Single ,那么你可以捕获一个On Error GoTo ...