2015-07-13 56 views
0

您好我正在使用一個函數,它將來自特定單元格的兩個輸入定義爲範圍。 當我運行代碼時,該函數將取得範圍的名稱,但不包含該值的名稱。 這些輸入的範圍位置是手動分配的,稍後將存儲公式的結果。 下面的代碼中,我突出顯示了問題部分 關於如何將範圍值應用到函數中的任何想法?如何將範圍的值分配給函數vba

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 

回答

0

你要麼需要將文本值連接成這樣的公式字符串:

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

,或者使用範圍的地址:

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

太感謝你了!羅裏!它現在工作完美 – Mariano