在VBA脚本中,在vlookup中返回“应用程序定义的错误或对象定义的错误”和“types不匹配”

我在下面的vba脚本有一些问题。 这很简单。 它意味着取得一个下拉列表的值,并根据另一个表中的是/否/空值进行响应。 代码工作正常,除了在停止脚本运行的vlookup行中有问题。

前两个vlookup行返回“应用程序定义或对象定义的错误”,第三个返回“数据types不匹配”错误。 公式引用的每个单元格被格式化为文本,所以我不确定问题是什么…任何反馈都会非常有帮助。 谢谢!

If Not Intersect(Target, Range("countryProductCell")) Is Nothing Then lastcolumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count cellRow = Target.Row defaultCellColumn = 4 Dim countryIndex As Variant countryIndex = Array(6, 6, 30, 21, 35, 29, 32, 20, 23, 18, 19, 34, 33, 22, 31, 26, 25, 27, 28, 7, 8, 15, 12, 10, 13, 11, 16, 17, 9) i = 0 For Each countryCell In Range(Cells(cellRow, 5), Cells(cellRow, lastcolumn)) 'If Default is selected 'If Not Target.Value = "(Select Title)" Then 'If Product is not selected If countryCell.Value = "Use Default" Then 'Look Up Purchaseablility, Needs Array If Not Application.VLookup(ActiveSheet.Cells(cellRow, defaultCellColumn), Sheets("Active Product Catalog").Range("E:AK"), countryIndex(i), False) = "Yes" Then 'If Not Purchaseable, Change Color countryCell.Interior.ColorIndex = 3 End If If Application.VLookup(ActiveSheet.Cells(cellRow, defaultCellColumn), Sheets("Active Product Catalog").Range("E:AK"), countryIndex(i), False) = "Yes" Then 'If Purchaseable, Change Color countryCell.Interior.ColorIndex = 35 End If Else If Application.VLookup(ActiveSheet.Cells(cellRow, countryCell.Column), Sheets("Active Product Catalog").Range("E:AK"), countryIndex(i), False) = "Yes" Then countryCell.Interior.ColorIndex = 35 End If End If 'Else 'End If i = i + 1 Next End If 

你定义了defaultCellColumn=4但在前两个公式中使用了未定义的variablesdefaultCell 。 在模块开始时使用Option Explicit是一个好主意,然后在编译时就会被捕获。

不知道第三个错误,但是你的countryIndex数组一直到35,这比E:AK的列数多。 认识到VLOOKUP使用相对于范围的列偏移 ,而不是绝对列 ,对于第三个参数(所以2 = F在你的情况下,35 = AM,超出你指定的范围,并会引发错误。

Data type mismatch错误可以使用下面的方法处理。

 On Error Resume Next Result = Application.VLookup(Cells(cellRow, countryCell.Column), Sheets("Active Product Catalog").Range("E:AK"), countryIndex(i), False) If Result = "Error 2042" Then Result = "Nothing Found" Else MsgBox Result End If On Error GoTo 0