2016-12-01 78 views
0

我有35到40工作表與每日股票數據,我試圖計算宏中每個工作表的股票收益率。公式是:LN(Today/Yesterday),它給出了每日股票收益。我正在運行下面的代碼,但我不知道如何在第5工作表中啓動循環。我的投資組合位於前四個工作表中。任何人都知道這將如何工作?從vba的第5個循環到最終的工作表?

Sub Macro2() 
Dim wb As Workbook 
Dim i As Integer 
Dim ws As Worksheet 
Set wb = ActiveWorkbook 
Set ws = Worksheets.Count = 5 

For i = 5 To ThisWorkbook.Worksheets.Count 
Activeworksheet.Columns("c").ClearContents 
Range("C4").Select 
ActiveCell.FormulaR1C1 = "=LN(RC[-1]/R[-1]C[-1])" 
Range("C4").Select 
Selection.AutoFill Destination:=Range("C4:C507") 
Range("C4:C507").Select 
Next i 

End Sub 

回答

1

您應該avoid using .Select,因爲這是相信它。這應有助於:

Sub Macro2() 
Dim wb As Workbook 
Dim i As Integer 
Dim ws As Worksheet 
Set wb = ActiveWorkbook 
Set ws = Worksheets.Count = 5 

For i = 5 To ThisWorkbook.Worksheets.Count 
With Worksheets(i) 
.Columns("c").ClearContents 
.Range("C4").FormulaR1C1 = "=LN(RC[-1]/R[-1]C[-1])" 
.Range("C4").AutoFill Destination:=.Range("C4:C507") 
Next i 

End Sub 

注意你如何有正確的理念,For循環開始我= 5是好的,但你那麼實際上從未使用i。當您使用ActiveSheet時,它(顯然是?)使用當前活動表單的任何內容。因此,您的代碼只會在該表單上運行......並且無論多少次您都有工作表(如果有意義的話)。

+0

謝謝布魯斯! –

+0

@NickGarcia是否適合你?如果是這樣,請將標記標記爲答案(單擊帖子左側的複選標記) – BruceWayne

0

想通了。繼承人代碼根據B3:B中的價格和C4中的退貨:C

Sub Macro2() 
Dim wb As Workbook 
Dim i As Integer 
Dim ws As Long 
Set wb = ActiveWorkbook 
For i = 6 To 56 
ws = Worksheets(i).Activate 
Range("C4").Select 
ActiveCell.FormulaR1C1 = "=LN(RC[-1]/R[-1]C[-1])" 
Range("C4").Select 
Selection.AutoFill Destination:=Range("C4:C507") 
Range("C4:C507").Select 
Range("C2").Select 
ActiveCell.FormulaR1C1 = "Daily Return" 
Range("C:C").Select 
Columns("C:C").EntireColumn.AutoFit 
Range(Selection, Selection.End(xlDown)).Select 
Range(Selection, Selection.End(xlDown)).Select 
Selection.Style = "Percent" 
Selection.NumberFormat = "0.0%" 
Selection.NumberFormat = "0.00%" 
With Selection 
    .HorizontalAlignment = xlCenter 
    .VerticalAlignment = xlBottom 
    .WrapText = False 
    .Orientation = 0 
    .AddIndent = False 
    .IndentLevel = 0 
    .ShrinkToFit = False 
    .ReadingOrder = xlContext 
    .MergeCells = False 
End With 
Range("B:B").Select 
Range(Selection, Selection.End(xlDown)).Select 
Selection.Style = "Currency" 
Next i 

End Sub 
+0

請注意,我的數據停在最初工作表中的工作表56上。 –

相關問題