2017-09-04 612 views
0

我正在嘗試編寫一個VBA宏,它通過計算直接在其上方和下方的單元格的平均值,將值分配給特定單元格。我通過選擇開發工具欄上的宏按鈕來運行它,然後我必須鍵入我的函數的名稱(它不會出現在列表中)「interpprob」並選擇運行。然後我得到一個彈出窗口,其中指出「參數不是可選的」。我不太確定問題是什麼。完整的宏在下面。 「tstep」意味着需要更改一些單元格值的一組行的數組。VBA「參數不可選」 - 不確定如何聲明變量

Function interpprob(f As Integer, d As Integer, spec As String, tstep As Long, above As Long, below As Long, i As Integer, j As Integer) 

f = 41 
d = 441 
spec = ETHA 

tstep(0) = f 
tstep(1) = f + d 
tstep(2) = f + 2 * d 
tstep(3) = f + 5 * d 

For i = 0 To 4 
    For j = 52 To 57 
     above = Cells(tstep(i) - 1, j).Value 
     below = Cells(tstep(i) + 1, j).Value 
     Sheets(spec).Cells(tstep(i), j).Value = (above + below)/2 
    Next j 
Next i 

End Function 

感謝, BL袋鼠

+0

確保您使用全部8個參數調用'interpprob'。 – miroxlav

+0

這將如何完成?只需輸入「interpprob(f,d,spec,tstep,above,below,i,j)」? –

+0

您需要實際值(參數)來代替這8個參數。你有什麼想法,你會把'f','d','spec'等放在什麼位置? – miroxlav

回答

1

根據您的期望,改變FunctionSub並刪除參數。

Sub interpprob() 

    f = 41 
    d = 441 
    spec = "ETHA" 

    tstep(0) = f 
    tstep(1) = f + d 
    tstep(2) = f + 2 * d 
    tstep(3) = f + 5 * d 

    For i = 0 To 3 'Changed from 4 as you do not assign a value to tstep(4) 
     For j = 52 To 57 
      above = Cells(tstep(i) - 1, j).Value 
      below = Cells(tstep(i) + 1, j).Value 
      Sheets(spec).Cells(tstep(i), j).Value = (above + below)/2 
     Next j 
    Next i 

End Sub 

您還可以插入下面的聲明只是Sub後:

Dim f As Long 
Dim d As Long 
Dim spec As String 
Dim tstep(0 To 3) As Long 
Dim above As Long 
Dim below As Long 
Dim i As Long 
Dim j As Long 

這是當一個程序的增長,其不負有心人做法。它可以讓你安全避免幾種錯誤。

爲了使這種做法強制性的,插入以下指令作爲文件的第一行(一切只是前):

Option Explicit 

您還可以看到該類型IntegerLong替換,因爲Integer是太短(-32768 ... +32767),對於標準使用而言並不現實,並且保持IntegerLong都沒有真正的好處(並且具有性能損失)。只需聲明每個整數變量爲Long

建議和修復的積分轉到YowE3KrobinCTS

+1

現在使用'Long'而不是'Integer'是目前最好的練習,所以我不擔心它(特別是考慮到OP使用了'Integer') - 我會+1原樣。 – YowE3K

+0

我做了幾個編輯,因爲試圖使用'tstep(4) - 1'作爲一個行將崩潰。 – YowE3K

+0

感謝您提出這些建議,我相信我現在可以開展工作! –