学以致用——使用VBA实现冒泡法排序随机数和随机日期(Bubble sorting of random number and date with VBA)

还记得以前考计算机等级考试四级时,用C语言实现过一些很基本的算法,其中就包括冒泡排序法。

今天,试着用VBA来实现以下冒泡排序。

程序特点:

1. 随机生成数字和日期

2. 实现对日期的排序

3. 添加了程序参数,方便控制排序类型(可以关闭不需要的排序操作)

4. 体验了Option Explicit (强制显式声明变量)功能


运行效果:


代码:

Option Explicit
Sub NestedLoop()
    Dim i, j As Integer '循环控制变量
    Dim t As Integer '随机数排序时的中间变量
    Dim td As Date '随机日期排序时的中间变量
    Dim sd As Date '随机生成日期时的起始日期
    Dim s1 As Boolean '控制是否执行随机数排序
    Dim s2 As Boolean '控制是否执行随机日期排序

    '设置程序参数
    s1 = True   'True -> 执行随机数排序
    s2 = True   'True -> 执行随机日期排序
    Const n As Integer = 20 '循环次数
    sd = #11/29/1980#  '起始日期
    
    '设置表头
    With Worksheets("BubbleSort")
        .Cells(1, 1) = "序号"
        .Cells(1, 2) = "随机数(排序前)"
        .Cells(1, 3) = "排序后随机数"
        .Cells(1, 4) = "随机日期(排序前)"
        .Cells(1, 5) = "排序后随机日期"
    End With
    
    
    '数据区
    With Worksheets("BubbleSort")
    For i = 1 To n
        .Cells(i + 1, 1) = i '序号(1,2,...,20)
        .Cells(i + 1, 2) = Int(Rnd * 20) + 1 '随机数(1-20)
        .Cells(i + 1, 4) = DateAdd("d", Int(Rnd() * (Date - sd)) + 1, sd) '随机日期
        'Debug.Print .Cells(i + 1, 4)
    Next
    
    '复制随机数
    For i = 1 To n
        .Cells(i + 1, 3) = .Cells(i + 1, 2)
        .Cells(i + 1, 5) = .Cells(i + 1, 4)
    Next
    
    '冒泡法排序随机数
    If s1 Then
    For i = 2 To n '外循环
        For j = i + 1 To n + 1 '内循环
            If .Cells(i, 3) < .Cells(j, 3) Then
            t = .Cells(i, 3)
            .Cells(i, 3) = .Cells(j, 3)
            .Cells(j, 3) = t
            End If
        Next
    Next
    End If
    
    '冒泡法排序随机日期
    If s2 Then
    For i = 2 To n '外循环
        For j = i + 1 To n + 1 '内循环
            If .Cells(i, 5) < .Cells(j, 5) Then
            td = .Cells(i, 5)
            .Cells(i, 5) = .Cells(j, 5)
            .Cells(j, 5) = td
            End If
        Next
    Next
    End If
    End With
End Sub

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值