退出'While'循环时,我的VBA代码意外中止。为什么?

时间:2012-10-16 06:18:38

标签: excel vba

我是VBA编码新手。我在Javascript和C ++中做了一些编码,所以我理解这些概念。不过,我对VBA的细节并不太熟悉。此特定代码适用于Excel 2007. sort函数是从其他位置复制为伪代码(文档不是我的)。我把它重写为VBA(不成功)。

此代码无法正常运行。代码突然完全中止(不仅仅是跳出循环或函数,而是在经过While循环两次后完全退出。

要复制问题,请将此代码另存为Excel工作表的宏,在B5中键入数字9853,在B6中键入“= Kaprekar(B5)”。基本上,运行Kaprekar(9853)。

有人可以帮我弄清楚我在这里做错了什么吗?感谢。

顺便说一句,我现在正在使用While-Wend。我也尝试过Do While-Loop,结果相同。

以下是代码:

Function Sort(A)
    limit = UBound(A)
    For i = 1 To limit
        ' A[ i ] is added in the sorted sequence A[0, .. i-1]
        ' save A[i] to make a hole at index iHole
        Item = A(i)
        iHole = i
        ' keep moving the hole to next smaller index until A[iHole - 1] is <= item
        While ((iHole > 0) And (A(iHole - 1) > Item))
            ' move hole to next smaller index
            A(iHole) = A(iHole - 1)
            iHole = iHole - 1
        Wend
        ' put item in the hole
        A(iHole) = Item
    Next i
    Sort = A
End Function

Function Kaprekar%(Original%)

    Dim Ord(0 To 3) As Integer

    Ord(0) = Original \ 1000
    Ord(1) = (Original - (Ord(0) * 1000)) \ 100
    Ord(2) = (Original - (Ord(1) * 100) - (Ord(0) * 1000)) \ 10
    Ord(3) = (Original - (Ord(2) * 10) - (Ord(1) * 100) - (Ord(0) * 1000))

    If (Ord(0) = Ord(1)) * (Ord(1) = Ord(2)) * (Ord(2) = Ord(3)) * (Ord(3) = Ord(0)) = 1 Then
        Kaprekar = -1
        Exit Function
    End If

    Arr = Sort(Ord)

    Kaprekar = Ord(3)
End Function

1 个答案:

答案 0 :(得分:4)

excel评估while语句中的两个项目,所以

While ((ihole > 0) And (A(ihole - 1) > item))

当ihole = 0时,第一次测试返回false,第二次测试超出界限,用 #Value 错误轰炸出函数。

快速的冒泡就是这样的:

Option Explicit
Function Sort(A)
Dim iLoop As Long
Dim jLoop As Long
Dim Last As Long
Dim Temp

Last = UBound(A)

For iLoop = 0 To Last - 1
    For jLoop = iLoop + 1 To Last
        If A(iLoop) > A(jLoop) Then
            Temp = A(jLoop)
            A(jLoop) = A(iLoop)
            A(iLoop) = Temp
        End If
    Next jLoop
Next iLoop
Sort = A
End Function