1. 程式人生 > >Access2010中調用過程帶call與不帶call的問題

Access2010中調用過程帶call與不帶call的問題

Access201 vba 過程調用 call

今天在上課,給學生講到了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的調用,悲劇的事情發生了,給出如下提示:
技術分享圖片
明顯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

Access2010中調用過程帶call與不帶call的問題