无法在excel的开发人员模式下运行冒泡排序

ui7jx7zq  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(161)

我试图在excel中运行一个简单的冒泡排序算法。每次我试图运行冒泡排序时,我都会收到一个错误消息,“编译错误子函数或函数未定义。”我正在使用教授给我的代码。请帮助。

Sub BubbleSort()

'   Sorts an array using bubble sort algorithm

For i = 1 To 20
    For j = 1 To 20 - i
            If Cells(j, 1) > Cells(j + 1, 1) Then
            Temp = Cells(j, 1)
            Sleep 10
            Cells(j, 1) = Cells(j + 1, 1)
            Cells(j + 1, 1) = Temp
            
            
        Application.Wait (Now + TimeValue("0:00:001"))
            
            
        End If
    
    Next
Next



End Sub

我试过使用vb sytax检查器。但坦率地说,我没有vb的经验,不知道从哪里开始。

idfiyjo8

idfiyjo81#

对单列区域进行气泡排序

    • 快速修复**
Option Explicit

' Sorts the range A1:A20 using the bubble sort algorithm
Sub BubbleSort()

    Const FIRST_ROW As Long = 1
    Const LAST_ROW As Long = 20

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve
 
    Dim Temp, i As Long, j As Long

    For i = FIRST_ROW To LAST_ROW - 1
        For j = i + 1 To LAST_ROW
            If ws.Cells(i, "A").Value > ws.Cells(j, "A").Value Then
                Temp = ws.Cells(i, "A").Value
                ws.Cells(i, "A").Value = ws.Cells(j, "A").Value
                ws.Cells(j, "A").Value = Temp
            End If
        Next j
    Next i

    MsgBox "Column range sorted.", vbInformation

End Sub
ulydmbyx

ulydmbyx2#

Sleep是一个Windows函数而不是VBA函数,但您仍可以在声明该函数后调用Windows Sleep API,从而在VBA代码中使用该函数
例如:

#If VBA7 Then
 Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
 Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds as Long) 'For 32 Bit Systems
#End If

更好的替代方法是使用Application.Wait
下面是等待10秒钟的工作代码

Sub BubbleSort() '   Sorts an array using bubble sort algorithm

For i = 1 To 20
    For j = 1 To 20 - i
            If Cells(j, 1) > Cells(j + 1, 1) Then
            Temp = Cells(j, 1)
            Application.Wait ("00:00:10")

            Cells(j, 1) = Cells(j + 1, 1)
            Cells(j + 1, 1) = Temp
            
            
        Application.Wait (Now + TimeValue("0:00:001"))
            
            
        End If
    
    Next

下一个结束子组件

相关问题