Hi, Folks,
I'm a VBA neophyte, bumbling my way through what I'd hoped would be a simple test program. I've created a sub (Test1) that compares a user entered number with a randomly generated number, and if they match declares them a winner. I then created a Command Button that, when clicked, will run this sub. Lovely.
I then tried to user Application.OnKey inside a Worksheet_Change sub such that when "Enter" is pressed, the Test1 sub will fire. Unfortunately, when I press the button, I get the "Cannot run the macro..." error. I've enabled macros, and since the Command Button macro works just fine, I'm not sure what the problem could be. I've included both a screenshot and the code, so any help is appreciated.
Thanks!
I'm a VBA neophyte, bumbling my way through what I'd hoped would be a simple test program. I've created a sub (Test1) that compares a user entered number with a randomly generated number, and if they match declares them a winner. I then created a Command Button that, when clicked, will run this sub. Lovely.
I then tried to user Application.OnKey inside a Worksheet_Change sub such that when "Enter" is pressed, the Test1 sub will fire. Unfortunately, when I press the button, I get the "Cannot run the macro..." error. I've enabled macros, and since the Command Button macro works just fine, I'm not sure what the problem could be. I've included both a screenshot and the code, so any help is appreciated.
Thanks!
Code:
Sub CommandButton1_Click()
Test1
End Sub
Sub Test1()
Dim numberEnteredByUser As Integer
numberEnteredByUser = Cells(1, 1).Value
If numberEnteredByUser < 1 Or numberEnteredByUser > 10 Then
MsgBox "Enter a number between 1 and 10."
Exit Sub
End If
Dim RandomNum As Integer
Randomize
RandomNum = Int((10 - 1 + 1) * Rnd + 1)
Cells(2, 1) = RandomNum
If numberEnteredByUser = RandomNum Then
Cells(4, 1).Value = "Winner!"
Cells(1, 7) = Cells(1, 7) + 1 'Update the Win total
Else
Cells(4, 1).Value = ""
Cells(2, 7) = Cells(2, 7) + 1 'Update the Losses total
End If
Cells(1, 1) = ""
End Sub
Sub Worksheet_Change(ByVal Target As Range)
'Application.OnKey "{RETURN}", "thing"
Application.OnKey "{ENTER}", "Test1"
End Sub
