我收到运行时错误'13':在以下代码中键入不匹配。根据我对这个错误的理解,它似乎是由公式中有两种类型的变量引起的。这对我来说有点正确,因为我的索引匹配函数将单元格与数字连接,单元格与文本一起返回一个数字。我试图将数字格式化为文本,但不断收到相同的错误。这似乎是问题吗?如果是这样,是否有人知道这种/不同方式的解决方法,我正在尝试做什么?谢谢!
Sub Lookup2()
Dim cell As Range
Dim lookUp1Sht As Worksheet
Dim lookUp2Sht As Worksheet
Dim lookUp2Rng As Range
Dim val1 As Variant
Set lookUp1Sht = ThisWorkbook.Worksheets("New")
Set lookUp2Sht = ThisWorkbook.Worksheets("input")
Set lookUp2Rng = ThisWorkbook.Worksheets("comp").Range("A1:C136")
For Each cell In Range("CaliforniaL")
With cell '
Select Case True
Case IsNumeric(.Value)
.Offset(0, 1).Value = CDbl(.Value)
Case Else
.Offset(0, 1).Value = (Application.WorksheetFunction.Index(lookUp2Sht.Range("K:K"), Application.WorksheetFunction.Match(cell.Value & cell.Offset(0, -3), lookUp2Sht.Range("A:A") & lookUp2Sht.Range("H:H"), 0)))
End Select
End With
Next
End Sub
答案 0 :(得分:0)
我猜这个问题出在这个部分:
cell.Value & cell.Offset(0, -3)
cell.value
正在返回单元格中的数据,而cell.Offset
returns a range object。由于Match
函数需要lookup_value
,并且由于无法连接值和范围对象,因此会导致错误。实际上,您根本无法连接范围,因此匹配函数的第二个参数也将失败:
lookUp2Sht.Range("A:A") & lookUp2Sht.Range("H:H")
如果您将这些公式放在工作表的单元格中(例如,=match(A2 & d2, A:A & H:H, 0)
,您会发现它们无效。
我从来没有看到在VBA代码中使用工作表函数的价值。我并不是说没有价值,只是因为我从未见过需要。
答案 1 :(得分:0)
我写了一个执行“双”匹配的函数。 (可能有一个在Excel中可用,但我太懒了,无法查找它。)使用它,并根据您的注释中的一些说明,您的代码可以重写如下:
Sub Lookup2()
Dim cell As Range
Dim lookUp1Sht As Worksheet
Dim lookUp2Sht As Worksheet
Dim lookUp2Rng As Range
Dim val1 As Variant
Set lookUp1Sht = ThisWorkbook.Worksheets("New")
Set lookUp2Sht = ThisWorkbook.Worksheets("input")
Set lookUp2Rng = ThisWorkbook.Worksheets("comp").Range("A1:C136")
For Each cell In Range("CaliforniaL")
With cell
If IsNumeric(.Value) Then
.Offset(0, 1).Value = CDbl(.Value)
Else
val1 = DoubleMatch(lookUp1Sht.Cells(.Row, "A").Value, lookUp2Sht.Range("A:A"), _
lookUp1Sht.Cells(.Row, "L").Value, lookUp2Sht.Range("H:H"))
If IsError(val1) Then
.Offset(0, 1).Value = val1
Else
.Offset(0, 1).Value = lookUp2Sht.Cells(val1, "K").Value
End If
End If
End With
Next
End Sub
Function DoubleMatch(Key1 As Variant, Range1 As Range, Key2 As Variant, Range2 As Range) As Variant
'This function only performs an "Exact Match"
If Range1.Rows.Count <> Range2.Rows.Count Then
DoubleMatch = CVErr(xlErrRef)
Exit Function
End If
If Range1.Columns.Count > 1 Or Range2.Columns.Count > 1 Then
DoubleMatch = CVErr(xlErrRef)
Exit Function
End If
Dim c As Range
Dim r As Long
Dim address1 As String
With Range1
Set c = .Find(What:=Key1, LookIn:=xlValues, LookAt:=xlWhole)
If c Is Nothing Then
DoubleMatch = CVErr(xlErrNA)
Exit Function
End If
address1 = c.Address
Do
r = c.Row - Range1.Row + 1
If Key2 = Range2(r, 1).Value Then
DoubleMatch = r
Exit Function
End If
Set c = .Find(What:=Key1, LookIn:=xlValues, LookAt:=xlWhole, After:=c)
If c Is Nothing Then
DoubleMatch = CVErr(xlErrNA)
Exit Function
End If
If c.Address = address1 Then
DoubleMatch = CVErr(xlErrNA)
Exit Function
End If
Loop
End With
DoubleMatch = CVErr(xlErrNA)
End Function