使用VBA Excel创建自定义函数,错误#VALUE

时间:2015-07-23 10:56:57

标签: excel vba function excel-vba

Public Function CopperThermalConductivity(T As Double, RRR As Double)

    Dim P1, P2, P3, P4, P5, P6, P7 As Double
    Dim W0, W1, W10 As Double
    Dim Beta, BetaR As Double

    Beta = 0.634 / RRR
    BetaR = Beta / 0.0003

    P1 = 0.00000001754
    P2 = 2.763
    P3 = 1102
    P4 = -0.165
    P5 = 70
    P6 = 1.756
    P7 = 0.838 / (BetaR ^ 0.1661)

    W0 = Beta / T
    W1 = (P1 * (T ^ P2)) / (1 + (P1 * P3 * (T ^ (P2 + P4)) * WorksheetFunction.Exp(-(P5 / T) ^ P6)) + W0)
    W10 = (P7 * W1 * W0) / (W1 + W0)

    CopperThermalConductivity = (1 / (W0 + W1 + W10))

End Function

Sub DescribeFunctionCopper()
   Dim FuncName As String
   Dim FuncDesc As String
   Dim ArgDesc(1 To 2) As String

   FuncName = "CopperThermalConductivity"
   FuncDesc = "Returns the Thermal Conductivity in W/m-K"

   ArgDesc(1) = "Temperature in Kelvin"
   ArgDesc(2) = "Residual-resistivity ratio"

   Application.MacroOptions _
      Macro:=FuncName, _
      Description:=FuncDesc, _
      ArgumentDescriptions:=ArgDesc, _
      Category:="Cryogenics"
End Sub

我写了一些代码来为Excel创建一个可访问的函数。不知何故,当我在Excel上使用此函数时,我得到#VALUE错误,任何想法?构建宏时,我没有收到任何错误。请帮帮我。

1 个答案:

答案 0 :(得分:0)

这一行是错误的来源:

W1 = (P1 * (T ^ P2)) / (1 + (P1 * P3 * (T ^ (P2 + P4)) * WorksheetFunction.Exp(-(P5 / T) ^ P6)) + W0)

您无法在VBA代码中使用工作表函数EXP。 VBA等效Exp(),应该使用它而不是工作表函数。

顺便提一下,当你声明这样的变量时,请注意:

Dim P1, P2, P3, P4, P5, P6, P7 As Double
Dim W0, W1, W10 As Double
Dim Beta, BetaR As Double

P7W10BetaR声明为Double,其他声明为Variant。如果你想将所有这些变量声明为Double,你应该这样做:

Dim P1 As Double, P2 As Double, P3 As Double, P4 As Double, P5 As Double, P6 As Double, P7 As Double
Dim W0 As Double, W1 As Double, W10 As Double
Dim Beta As Double, BetaR As Double