VBA“参数不可选” – 不确定如何声明variables

我正在尝试编写一个VBAmacros,它通过计算直接在它上面和下面的单元格的平均值,将值分配给特定的单元格。 我正在运行它通过select开发工具栏上的macrosbutton,然后我必须键入我的function(它不出现在列表中)“interpprob”的名称,并select运行。 然后我得到一个popup窗口,指出“参数不是可选的”。 我不太确定问题是什么。 下面是完整的macros。 “tstep”意味着需要更改某些单元格值的一组行的数组。

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 Roo

根据您的期望,将Function更改为Sub并删除参数。

 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没有真正的好处(并且有性能损失)。 只要将每个整数variables声明为Long

build议和修复的积分转到YowE3K和robinCTS 。