头像
返回

[项目实践] VBA Excel自制猜数游戏

本帖最后由 Gr3yPh4ntom 于 2025-2-13 11:40 编辑

初学VBA语言,如有纰漏详请各位大佬指出,本人必将重谢
  1. ' 初始化所需变量
  2. Dim isPlaying As Boolean
  3. Dim correctNumber As Integer
  4. Dim userInput As Integer
  5. Dim inputMessage As String


  6. Sub Auto_Open() ' 设置工作表打开时自动运行宏
  7.     Call initializeGame
  8. End Sub

  9. Sub initializeGame() ' 初始化游戏
  10.     Randomize
  11.     isPlaying = False
  12.     correctNumber = Int(100 * Rnd)
  13.     inputMessage = "开始猜数!输入数字"
  14.     msgBoxResult = MsgBox("欢迎来到猜数游戏,按是开始,按否退出", vbYesNo)
  15.     If msgBoxResult = vbYes Then
  16.         Call startGame ' 如果玩家按了Yes就开始游戏
  17.     Else
  18.         Exit Sub ' 如果玩家按了No就停止运行
  19.     End If
  20. End Sub

  21. Sub startGame() ' 游戏主过程
  22.     isPlaying = True
  23.     Do While isPlaying ' 只要玩家还在玩游戏就一直循环
  24.         userInput = CInt(InputBox(inputMessage))
  25.         If userInput = correctNumber Then
  26.             MsgBox "猜对了!你真NB"
  27.             isPlaying = False ' 退出循环
  28.         ElseIf userInput < correctNumber Then
  29.             inputMessage = "猜小了,再猜一遍"
  30.         Else
  31.             inputMessage = "猜大了,再猜一遍"
  32.         End If
  33.     Loop
  34.     Call initializeGame ' 一局结束后重新初始化游戏
  35. End Sub
回复

全部回复

初学
回复
我也说一句 回复1 收藏 返回
等待数据加载中,请稍后...
导航 顶部
头像游客

您还未登录,立即登录?

确定 取消