在Excel中运行Bubble Sort时出现编译错误:Sub或函数未定义
解决Excel VBA冒泡排序的“Sub or Function not defined”编译错误
编译错误的直接原因是代码中的Sleep 10调用了未定义的函数——VBA本身没有内置Sleep函数,该函数属于Windows系统API,必须先声明才能使用。
解决方法一:添加Windows API声明
在VBA模块的最顶部(所有Sub过程之外)添加Sleep函数的声明,之后即可正常使用:
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Sub BubbleSort() ' Sorts an array using bubble sort algorithm Dim i As Integer, j As Integer, Temp As Variant 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:00.001")) End If Next j Next i End Sub
解决方法二:替换为VBA内置等待方法
如果不想引入API,可以直接删除Sleep 10,或者用Application.Wait实现毫秒级等待(注意时间格式需包含毫秒部分):
Sub BubbleSort() ' Sorts an array using bubble sort algorithm Dim i As Integer, j As Integer, Temp As Variant For i = 1 To 20 For j = 1 To 20 - i If Cells(j, 1) > Cells(j + 1, 1) Then Temp = Cells(j, 1) Cells(j, 1) = Cells(j + 1, 1) Cells(j + 1, 1) = Temp ' 合并10毫秒+1毫秒的等待,总11毫秒 Application.Wait Now + TimeValue("0:00:00.011") End If Next j Next i End Sub
额外建议
在模块顶部添加Option Explicit,强制所有变量必须声明,能避免因变量未定义导致的潜在错误:
Option Explicit
内容的提问来源于stack exchange,提问作者Fernando Toranzo
相关产品推荐
相关产品推荐

