找不到Excel VBA公式类型不匹配错误

时间:2012-07-13 15:27:24

标签: excel vba excel-vba excel-formula

我遇到类型不匹配13错误,我看不到它在哪里。

这是代码。

Set concRange = Range(Cells(11, 48), Cells((10 + noDilutions), 48))
Set deadRange = Range(Cells(11, 49), Cells((10 + noDilutions), 49))
analysisSheet.Cells(f, 14).Value = _
    (WorksheetFunction.Lookup(WorksheetFunction.Index(deadRange, _
    WorksheetFunction.CountIf(deadRange, " >= " & _
    (WorksheetFunction.Max(deadRange) / 2))), deadRange, concRange)) _
    - (((WorksheetFunction.Index(deadRange, WorksheetFunction.CountIf _
    (deadRange, " >= " & (WorksheetFunction.Max(deadRange) / 2)))) _
    - (WorksheetFunction.Max(deadRange) / 2)) * ((WorksheetFunction.Lookup _
    (WorksheetFunction.Index(deadRange, WorksheetFunction.CountIf(deadRange, _
    " >= " & (WorksheetFunction.Max(deadRange) / 2))), deadRange, concRange)) _
    - (WorksheetFunction.Lookup(WorksheetFunction.Index(deadRange, _
    WorksheetFunction.CountIf(deadRange, " <= " & _
    (WorksheetFunction.Max(deadRange) / 2))), deadRange, concRange))) _
    / ((WorksheetFunction.Index(deadRange, WorksheetFunction.CountIf(deadRange, _
    " >= " & (WorksheetFunction.Max(deadRange) / 2)))) _
    - (WorksheetFunction.Index(deadRange, WorksheetFunction.CountIf _
    (deadRange, " <= " & (WorksheetFunction.Max(deadRange) / 2))))))

我尝试将“WorksheetFunction”更改为“Application”和“Application.WorksheetFunction”。

是的,这是一个非常长的公式:D

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:9)

首先,写出这样的公式是一个非常糟糕的主意,主要有三个原因:

  • 几乎不可能理解
  • 几乎不可能调试
  • 它重复了许多计算=效率低下

重构,它变成

With WorksheetFunction
    A = .Max(deadRange)
    B = .CountIf(deadRange, " >= " & (A / 2))
    C = .CountIf(deadRange, " <= " & (A / 2))
    D = .Index(deadRange, B)
    E = .Index(deadRange, C)
    F = .Lookup(D, deadRange, concRange)
    G = .Lookup(E, deadRange, concRange)

    analysisSheet.Cells(ff, 14).Value = _
        F - ((D - (A / 2)) * (F - G) / (D - E))
End With

调试此问题可以发现问题:spaces>=周围的.CountIf(deadRange, " >= " & (A / 2))是导致错误的原因。

所以,请改用

    B = .CountIf(deadRange, ">=" & (A / 2))
    C = .CountIf(deadRange, "<=" & (A / 2))