我正在使用VBA集成到Excel中。我在工作表上的组织表中有许多集成过程所需的变量,这些变量将根据需要进行更改。我已经编写了以下代码来完成此任务,并已成功调试了上述代码,从而可以正确编译。
Dim dIdt As Range
Dim Isnp As Range
Dim Tau As Range
Dim A As Range
Dim B As Range
Dim C As Range
Dim D As Range
Function Iscr(t)
Set dIdt = Worksheets("Sheet1").Range("F11").Value
Set Isnp = Worksheets("Sheet1").Range("F14").Value
Set Tau = Worksheets("Sheet1").Range("F13").Value
Iscr = (dIdt * t) + (Isnp * (Exp((-t) / Tau)))
End Function
Function Econd1A(t)
Set A = Worksheets("Sheet1").Range("B17").Value
Set B = Worksheets("Sheet1").Range("B18").Value
Set C = Worksheets("Sheet1").Range("B19").Value
Set D = Worksheets("Sheet1").Range("B20").Value
Econd1A = A + (B * (Log(Iscr(t)))) + (C * (Iscr(t))) + (D * (Iscr(t) ^ (1 / 2)) * Iscr(t))
End Function
Function Econd1(x0, t1, t2)
'define range of integral
int_range = t2 - t1
'discretize the integral into n slices dt wide
n = 1000
dt = int_range / n
'initialize variables
ta = t1
tb = ta + dt
Econd1 = x0
'calculate areas using trapezoidal rule
'sum area under curve of each slice
For j = 1 To n
Econd1 = Econd1 + (tb - ta) * (Econd1A(ta) + Econd1A(tb)) / 2
ta = tb
tb = ta + dt
Next
End Function
由于错误似乎与VBA无关,我现在在调试方面无所适从。
该单元格的预期输出为.0127,但它给出的是#VALUE!错误。
答案 0 :(得分:1)
Function Iscr(ByVal t As Double) As Double
Dim dIdt As Double, Isnp As Double, Tau As Double
dIdt = Worksheets("Sheet1").Range("F11").Value
Isnp = Worksheets("Sheet1").Range("F14").Value
Tau = Worksheets("Sheet1").Range("F13").Value
Iscr = (dIdt * t) + (Isnp * (Exp((-t) / Tau)))
End Function
Function Econd1A(ByVal t As Double) As Double
Dim A As Double, B As Double, C As Double, D As Double
A = Worksheets("Sheet1").Range("B17").Value
B = Worksheets("Sheet1").Range("B18").Value
C = Worksheets("Sheet1").Range("B19").Value
D = Worksheets("Sheet1").Range("B20").Value
Econd1A = A + (B * (Log(Iscr(t)))) + (C * (Iscr(t))) + (D * (Iscr(t) ^ (1 / 2)) * Iscr(t))
End Function
Function Econd1(ByVal x0 As Double, ByVal t1 As Double, ByVal t2 As Double) As Double
Dim int_range As Integer
int_range = t2 - t1
n = 1000
dt = int_range / n
ta = t1
tb = ta + dt
Econd1 = x0
For j = 1 To n
sEcond1 = sEcond1 + (tb - ta) * (Econd1A(ta) + Econd1A(tb)) / 2
ta = tb
tb = ta + dt
Next j
Econd1 = sEcond1
End Function
答案 1 :(得分:1)
Excel的计算引擎将用户定义的函数(UDF-从工作表单元格调用的自定义函数)中引发的所有错误包装起来,并产生#VALUE
单元格错误,而不是像损坏的VBA代码那样正常地爆炸。无需进行任何错误处理,调试UDF会很“有趣”。
实施错误处理:
Public Function MyUDF(args)
On Error GoTo ErrHandler
'...code...
Exit Function
ErrHandler:
Debug.Print Err.Description
Stop ' halts execution
Resume 'jumps back to the error-raising statement
End Function
在VBE中使立即窗格可见(Ctrl + G),然后计算一个正在调用UDF的工作表,其中包含可能覆盖所有边缘情况的多个可能的输入-特别注意值会导致溢出和除以零错误。
在Stop
关键字处停止执行时,按F8键运行Resume
语句,这将使您直接进入引起错误的语句-从此处可以检查所有涉及的变量,然后逐步浏览功能以验证数学执行过程-您还可以将“当前指令”黄线移回到已经执行的语句上,以重新运行它-只是将黄色箭头拖到函数中所需的位置,或右键单击指令并选择“设置下一条语句”。
一旦您知道该函数按预期工作,就可以删除该错误处理/调试代码,并且可以接受给定无效参数的#VALUE
错误。