将输入框数据条目转换为单元格数据条目

时间:2016-02-02 22:28:51

标签: excel vba excel-vba do-while

我想在不使用输入框的情况下创建一个猜谜游戏。我希望代码在A列上读取我的猜测,然后告诉我C列中是否正确。宏是数字1 - 10,宏应该经过每次猜测。

这是我的代码 -

Sub VBAGuessingGame()
Dim Secret As Integer
Dim Guess As Integer
Dim Tries As Integer

Randomize  'Initializes random-number generator

Secret = Int((10 * Rnd) + 1) 'Generates a random number between 1 and 10

Guess = 0
Tries = 0

Do While Guess <> Secret
    Guess = InputBox("Guess a number between 1 and 10.")
    If Guess = Secret Then
        Tries = Tries + 1
        MsgBox ("You guessed the number!")
        MsgBox ("It took you " & Tries & " to guess the number")

    ElseIf Guess > Secret Then
        Tries = Tries + 1
        MsgBox ("Wrong. Too high. Try again.")
    Else
        Tries = Tries + 1
        MsgBox ("Wrong. Too low. Try again.")
    End If
Loop

End Sub

1 个答案:

答案 0 :(得分:0)

将它放在Sheet1(Sheet1)后面,如果那是您正在使用的工作表:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim Guess As Integer, Secret As Integer
ThisColumn = Target.Column
ThisRow = Target.Row
If IsNumeric(Target.Cells.Value) Then
    Guess = Target.Cells.Value
Else: Guess = 0
End If
Randomize
Secret = Int(10 * Rnd) + 1

If ThisColumn = 1 Then
    If Guess = Secret Then
        Cells(ThisRow, 3).Value = "Right"
    Else
        Cells(ThisRow, 3).Value = "Wrong"
    End If
       Cells(ThisRow, 4).Value = Secret
End If
End Sub