VBA"参数不可选" - 不确定如何声明变量

时间:2017-09-04 23:35:06

标签: arrays excel vba excel-vba

我正在尝试编写一个VBA宏,通过计算直接在其上方和下方的单元格的平均值来为特定单元格分配值。我通过选择开发人员工具栏上的宏按钮来运行它,然后我必须输入我的功能名称(它不会出现在列表中)" interpprob"并选择运行。然后我得到一个弹出窗口,声明"参数不是可选的。"我不太清楚问题是什么。完整的宏如下。 " 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

1 个答案:

答案 0 :(得分:1)

根据您的期望,将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

您还可以看到类型Integer已替换为Long,因为整数太短(-32768 ... + 32767)并且标准使用不实用且保留Integer并且Long没有真正的好处(并且有性能损失)。只需将每个整数变量声明为Long

有关建议和修正的信用转到YowE3KrobinCTS