简体   繁体   中英

Creating a custom function with VBA Excel, error #VALUE

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

I wrote some code to create an accessible function for Excel. Somehow when I use this function on Excel I get a #VALUE error, any idea? I don't get any error when I build the macro. Help me please.

This line is the source of error:

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

You cannot use worksheet function EXP in VBA code. There is VBA equivalent Exp() and it should be used instead of worksheet function.


By the way, note that when you declare variables like that:

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

only P7 , W10 and BetaR are declared as Double , other are declared as Variant . If you want to declare all those variables as Double you should do it like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM