2015-11-21 61 views
2

我在這段代碼中有一些問題,我的.Value不起作用。'For'循環中的平均值

一切工作正常,如果我做了我的硬編碼 - >>> .value的=「=平均(E2:E7)」

然而,當我做下面的下面,它不會工作。我敢肯定它是 - >範圍( 「E」 ........)

'Iterate average for close price per week 
Dim startOfWeek As Integer 
Dim endOfWeek As Integer 

numberOfWeek = 52 
startOfWeek = 2 
endOfWeek = 6 
secondRow = 2 

For i = 1 To numberOfWeek 
    range("J" + CStr(secondRow)).Select 
     With Selection 





      .Value = "=Average(" + range("E" + CStr(startOfWeek) + ":E" + CStr(endOfWeek)).Select + ")" 




      .Font.Bold = False 
     End With 
    secondRow = secondRow + 1 
    startOfWeek = startOfWeek + 5 
    endOfWeek = endOfWeek + 5 
Next i 

回答

1
  1. 無需引用的行數時添加CStr。你可以將它們全部刪除。
  2. 您可以擺脫所有選擇語句並直接使用該對象。

所以,你可以重構你的代碼是這樣的:

'Iterate average for close price per week 
Dim startOfWeek As Integer 
Dim endOfWeek As Integer 

numberOfWeek = 52 
startOfWeek = 2 
endOfWeek = 6 
secondRow = 2 

For i = 1 To numberOfWeek 

    With Range("J" & secondRow) 

     .Value = "=Average(E" & startOfWeek & ":E" & endOfWeek & ")" 
     .Font.Bold = False 

    End With 

    secondRow = secondRow + 1 
    startOfWeek = startOfWeek + 5 
    endOfWeek = endOfWeek + 5 

Next i 
+0

感謝但它是在紅色和錯誤「預期:語句結束」 –

+0

哦,我已經認識到存在丟失「 &「。 –

+0

.Value =「= Average(E」&CStr(startOfWeek)&「:E」&CStr(endOfWeek)&「)」 –