如何在vba

时间:2015-07-13 09:50:05

标签: excel-vba vba excel

您好我正在使用一个函数,它接受来自特定单元格的两个输入,这两个输入被定义为范围。 当我运行代码时,该函数采用范围的名称而不是其中的值。 手动分配这些输入的范围位置,然后在那里存储公式的结果。 在代码下方,我突出了问题的部分 关于如何将范围值应用到函数中的任何想法?

   Sub my_range()

   Dim RngWidth As Long, RngHeight As Long

   Dim MyAverage As Variant, MyStDev As Variant, MyMax As Variant, MyMin As
     Variant, MyCount As Variant

Dim StckReturns As Range

Dim MyAverage1 As Variant, MyStDev1 As Variant


Selection.End(xlToLeft).Select

Selection.End(xlUp).Select

Range(Selection, Selection.End(xlToRight)).Select

Range(Selection, Selection.End(xlDown)).Select

RngWidth = Selection.Columns.Count

RngHeight = Selection.Rows.Count

ActiveCell.Offset(0, RngWidth).Range("a1").Select

ActiveCell.FormulaR1C1 = "Daily Return"

ActiveCell.Offset(2, 0).Range("a1").Select

ActiveCell.FormulaR1C1 = "=StockReturn(R[-1]C[-1],RC[-1])"

Range(ActiveCell, ActiveCell).Select

Selection.AutoFill Destination:=Range(ActiveCell, ActiveCell.Offset(RngHeight - 3, 0))

Set StckReturns = Range(ActiveCell, ActiveCell.Offset(RngHeight - 3, 0))

MyAverage = InputBox("Where do you want the Average?")

MyStDev = InputBox("Where do you want the Standard Deviation?")

Range(MyAverage).Value = WorksheetFunction.Average(StckReturns.Value)

Range(MyStDev).Value = WorksheetFunction.StDev(StckReturns.Value)

MyAverage1 = Range(MyAverage).Value

MyStDev1 = Range(MyStDev).Value

ActiveCell.Offset(-2, 1).Range("a1").Select

ActiveCell.FormulaR1C1 = "Scaled Return"

ActiveCell.Offset(2, 0).Range("a1").Select

***ActiveCell.FormulaR1C1 = "=ScaledReturns(RC[-1],myaverage1,MyStDev1)"***

Range(ActiveCell, ActiveCell).Select

Selection.AutoFill Destination:=Range(ActiveCell, ActiveCell.Offset(RngHeight - 3, 0))


End Sub

Function StockReturn(IniPrice As Double, FinPrice As Double) As Double

StockReturn = (FinPrice - IniPrice) / IniPrice

End Function

Function ScaledReturns(MyReturn As Variant, AverageReturn As Variant, StDevReturn As Variant) As Double

ScaledReturns = (MyReturn - AverageReturn) / StDevReturn

End Function

1 个答案:

答案 0 :(得分:0)

您需要将文字值连接到公式字符串中,如下所示:

ActiveCell.FormulaR1C1 = "=ScaledReturns(RC[-1]," & myaverage1 & "," & MyStDev1 & ")"

或使用范围的地址:

ActiveCell.FormulaR1C1 = "=ScaledReturns(RC[-1]," & Range(myaverage).Address(referencestyle:=xlR1C1) & "," & Range(MyStDev).Address(referencestyle:=xlR1C1) & ")"