参考查找公式VBA

时间:2018-03-15 22:15:45

标签: vba indexing match lookup

希望有人可以帮助我。我有这一行代码,我无法理解为什么它会抛出 typemismatch 错误。我想要完成的是使用索引匹配来查找值并减去,除以,添加等。使用索引匹配拉取的另一个值。我到处搜索,看看是否还有其他类似问题没有成功。我已经为VBA编写了好几年了,但出于某种原因我对此感到难过。如果我取出第二个查找公式和方程符号,代码就会正确运行。但是,只要添加减号,加号或分号,就会出错。为方便起见,所有变量都变暗并正确设置。任何帮助,将不胜感激。代码如下。谢谢!

Dim qty as worksheet
Dim Imonth as integer, IImonth as integer
Dim lrow as long

With summary1
.Range("B3:B" & lrow).Formula =   Application.Iferror(Application.Index(qty.Columns(Imonth), Application.Match(.Range("A3:A" & lrow), qty.Columns(1), 0)) - Application.Index(qty.Columns(IImonth), Application.Match(.Range("A3:A" & lrow), qty.Columns(1), 0)), " ")

1 个答案:

答案 0 :(得分:0)

我会将所有内容加载到内存数组中然后循环它。

Sub kjlk()


Dim qty As Worksheet
Dim Imonth As Integer, IImonth As Integer
Dim lrow As Long
Dim summary1 As Worksheet

'assign the variables
Set qty = Worksheets("Sheet1")
Set summary1 = Worksheets("Sheet2")

Imonth = 20
IImonth = 21

lrow = 20

Dim IMArr As Variant
Dim IIMarr As Variant
Dim lkupArr As Variant

IMArr = Intersect(qty.Columns(Imonth), qty.UsedRange).Value
IIMarr = Intersect(qty.Columns(IImonth), qty.UsedRange).Value
lkupArr = Intersect(qty.Columns(1), qty.UsedRange).Value

Dim InArr As Variant
Dim OutArr As Variant



With summary1
    InArr = .Range("A3:A" & lrow).Value
    ReDim OutArr(1 To UBound(InArr, 1), 1 To 1)
    Dim i As Long
    For i = 1 To UBound(InArr, 1)
        Dim mtch As Long
        mtch = WhereContains(lkupArr, InArr(i, 1))
        If mtch > -1 Then
            OutArr(i, 1) = IMArr(mtch, 1) - IIMarr(mtch, 1)
        Else
            OutArr(i, 1) = vbNullString
        End If
    Next i
   .Range("B3:B" & lrow).Value= OutArr
End With
End Sub

Function WhereContains(arr, v) As Long
Dim rv As Long, i As Long
    rv = -1
    For i = LBound(arr) To UBound(arr)
        If arr(i, 1) = v Then
            rv = i
            Exit For
        End If
    Next i
    WhereContains = rv
End Function