为Sub分配值会生成编译错误:参数不可选

时间:2015-09-28 23:00:29

标签: excel-vba vba excel

当我尝试运行此宏时,我会收到一条消息

  

编译错误:参数不是可选的

它突出了最后一个等式中的pressureDrop。

Public Sub pressureDrop(p As Double, L As Double, _
                        D As Double, u As Double, _
                        e As Double, w As Double)

    Dim A As Double, B As Double, f As Double, k As Double
    Dim Re As Double, Rng1 As Range, Rng2 As Range

    Re = p * D * u / w

    With WorksheetFunction

        A = (2.457) * .Ln(1 / (7 / Re) ^ 0.9 + (0.27 * e / D))
        B = (37530 / Re) ^ 16
        f = 2 * ((8 / Re) ^ 12 + 1 / (A + B) ^ (3 / 2)) ^ (1 / 12)

        Set Rng1 = Range("D2:D29")
        Set Rng2 = Range("E2:E29")
        k = .SumProduct(Rng1, Rng2)

    End With

    pressureDrop = p * ((4 * f * (L / D) + k) * (u ^ 2) / 2)

End Sub

3 个答案:

答案 0 :(得分:0)

您还可以对另一个变量进行Dim并为其指定最终值,而不是将其分配给pressuredrop

Dim dAnswer as Double
dAnswer = p * ((4 * f * (L / D) + k) * (u ^ 2) / 2)

答案 1 :(得分:0)

将其更改为函数:

Public Function pressureDrop(...)
    ...

    pressureDrop = p * ((4 * f * (L / D) + k) * (u ^ 2) / 2)
End Function

答案 2 :(得分:0)

替换

Public Sub pressureDrop(p As Double, L As Double, _
                    D As Double, u As Double, _
                    e As Double, w As Double)

Public Function pressureDrop(p As Double, L As Double, _
                    D As Double, u As Double, _
                    e As Double, w As Double) as Double