2016-02-02 96 views
0

我想在不使用輸入框的情況下創建猜謎遊戲。我想讓代碼讀取列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 
+0

您將需要使用公共變量和worksheet_change事件。 –

回答

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