在按钮上运行Vba功能按下不能正常工作

时间:2016-04-08 12:22:46

标签: excel vba excel-vba

这是一个简单的股票价格变动代码 我的代码是函数(带参数)

    Function VanillaCall(S0 As Single, Exercise As Single, Mean As Single, sigma As Single, _
Interest As Single, Time As Single, Divisions As Integer, Runs As Integer) As Single

deltat = Time / Divisions
interestdelta = Exp(Interest * deltat)
up = Exp(Mean * deltat + sigma * Sqr(deltat))
down = Exp(Mean * deltat - sigma * Sqr(deltat))
pathlength = Int(Time / deltat)

piup = (interestdelta - down) / (up - down)
pidown = 1 - piup
Temp = 0

For Index = 1 To Runs
    upcounter = 0
    For j = 1 To pathlength
        If Rnd > pidown Then upcounter = upcounter + 1
    Next j
        callvalue = Application.Max(S0 * (up ^ upcounter) * (down ^ (pathlength - upcounter)) - Exercise, 0) / (interestdelta ^ pathlength)
        Temp = Temp + callvalue
Next Index

VanillaCall = Temp / Runs

End Function

参数从excel中的单元格传递。 我想从按钮单击执行此功能,并在单元格中显示返回值,例如b12。 我已经尝试将代码放在一个按钮sub但它不工作,一个调用vanillacall内部sub也不工作。 像..

private sub button1_click()
call vanillacall
end sub

3 个答案:

答案 0 :(得分:1)

Private Sub button1_click()
    Range("B12").Value = vanillacall(....)
End Sub

根据您的要求,在Range中传递参数,如下所示。下面的代码就是例如(由于excel数据的变化)

Sub testing33()
    Range("B12") = sample(Range("A5"), Range("B5"))
End Sub

Function sample(a As Range, b As Range)
     sample = a.Cells.Value & ", " & b.Cells.Value
End Function

答案 1 :(得分:1)

我会做类似下面的事情,这将允许我选择包含我想传递给函数的数据的范围(只要范围是连续的并且包含8个单元格)并选择我想要输出的单元格结果到了。

ui-bootstrap-tpls.js

答案 2 :(得分:0)

您需要从工作表中获取值并保存在变量中。然后将变量传递给函数。然后将结果输出到某处的工作表。您需要根据需要调整范围地址和工作表名称。

Private sub button1_click()

    dim ws as worksheet
    Set ws = worksheets("Sheet1") ' < change the sheet name as appropriate

    dim S0 As Single
    dim Exercise As Single
    dim Mean As Single 
    dim sigma As Single
    dim Interest As Single
    dim Time As Single
    dim Divisions As Integer
    dim Runs As Integer As Single

    S0 = ws.Range("B1") '< specify the cell that has this data
    Exercise = ws.Range("B2") '< specify the cell that has this data
    Mean   = ws.Range("B3") '< specify the cell that has this data
    sigma  = ws.Range("B4") '< specify the cell that has this data
    Interest  = ws.Range("B5") '< specify the cell that has this data
    Time  = ws.Range("B6") '< specify the cell that has this data
    Divisions  = ws.Range("B7") '< specify the cell that has this data
    Runs = ws.Range("B8") '< specify the cell that has this data

    dim Result as Single
    Result = vanillacall(S0, Exercise , Mean, sigma, Interest, Time, Divisions, Runs)
    ws.Range("B10") = Result '<specify the cell where you want the result

end sub