今天在上课,给学生讲到了access2010中过程的调用,在印象中见过的access2010的材料都提到:过程的调用call是可以省略的。可在上课时就出现的问题了!!!
一、 情境再现
在讲解过程的作用之一:可以减少代码的重复提高共享效率。用了下面这段代码:

Private Sub numSort()
    '产生20个[0,100]之间的整型随机数
    Dim n(1 To 20) As Integer
    Dim i As Integer
    For i = 1 To 20
        Randomize
        n(i) = Rnd() * 101
    Next
    '打印排序前随机数
    Dim outString As String
    outString = "排序前随机数:"
    For i = 1 To 20
        outString = outString & Str(n(i)) & "  "
    Next
    Debug.Print outString
    '排序
    Dim temp As Integer
    Dim j As Integer
    For i = 1 To 20
        For j = i To 20
            If (n(i) > n(j)) Then
                temp = n(i)
                n(i) = n(j)
                n(j) = temp
            End If
        Next
    Next
    '打印排序后随机数
    outString = "排序后随机数:"
    For i = 1 To 20
        outString = outString & Str(n(i)) & "  "
    Next
    Debug.Print outString
End Sub

例题的目的是:产生20个随机数存于数组,数组打印出来,对20个随机数从小到大排序,数组再打印出来。
这里面用到了两次的数组打印,两段代码有共同性,可以提练成一个过程从而减少代码、提高代码复用率。于是在课堂上开始给学生修改代码了(原本以为是简单的事,事前没有先验证,结果笑话了….@~)。修改后的代码如下:

Private Sub numSort()
    '产生20个[0,100]之间的整型随机数
    Dim n(1 To 20) As Integer
    Dim i As Integer
    For i = 1 To 20
        Randomize
        n(i) = Rnd() * 101
    Next
    '打印排序前随机数
    printArr("排序前的随机数:",n)
    '排序
    Dim temp As Integer
    Dim j As Integer
    For i = 1 To 20
        For j = i To 20
            If (n(i) > n(j)) Then
                temp = n(i)
                n(i) = n(j)
                n(j) = temp
            End If
        Next
    Next
    '打印排序后随机数
End Sub
Private Sub printArr(s As String, k() As Integer)
    Dim outString As String
    outString = s
    Dim i As Integer
    For i = LBound(k) To UBound(k)
        outString = outString & Str(k(i)) & "  "
    Next
    Debug.Print outString
End Sub

在定义好printArr过程,要调用时使用不带call的调用,悲剧的事情发生了,给出如下提示:
Access2010中调用过程带call与不带call的问题_第1张图片
明显printArr("排序前的随机数:",n)这个语句出问题了。可是怎么看从语法上都没有问题(唉…这就是治学不严的后果,谨记,切记,以后不再范),后面试了下把call加上,改成:
Call printArr("排序前的随机数:",n)
问题解决!!!
二、 问题总结
后面又通过几个例子试了下。发现:
如果过程的参数中包含有数组的参数,则call一定要加上;
否则call可以省略。
三、 经验教训

  1. 作为一名教书匠,传授给学生的知识时,自己一定要谨慎验证,谨慎、谨慎、再谨慎,验证、验证、再验证,不然容易误人子弟…
  2. 经验主义不可取,一定谨记
    另:为了代码更方便移植、更通用,上面代码可优化成(使用符号常量与使用lbound与ubound两个系统函数)
    
    Option Compare Database
    Private Const ARR_LOW = 1   '数组上标
    Private Const ARR_UPP = 20  '数组下标

Private Sub numSort()
Dim n(ARR_LOW To ARR_UPP) As Integer
Dim i As Integer
For i = LBound(n) To UBound(n)
Randomize
n(i) = Rnd() * 101
Next
'打印排序前随机数
Call printArr("排序前的随机数:", n)

'排序
Dim temp As Integer
Dim j As Integer
For i = LBound(n) To UBound(n)
    For j = i To UBound(n)
        If (n(i) > n(j)) Then
            temp = n(i)
            n(i) = n(j)
            n(j) = temp
        End If
    Next
Next
'打印排序后随机数
Call printArr("排序后的随机数:", n)

End Sub