基本上我想循环以下操作,直到我按下{DOWN}
,但私有Sub似乎不是100%正确,因此代码只是永远循环。
Public pressdown As Boolean
Sub DemoOnKey()
Application.OnKey "{RIGHT}", "moveright"
Application.OnKey "{LEFT}", "moveleft"
Application.OnKey "{DOWN}", "movedown"
Application.OnKey "{UP}", "moveup"
End Sub
Sub moveright()
Do Until pressdown
Selection.Copy Destination:=Selection.Offset(0, 1)
Selection.Offset(0, 1).Select
Selection.Offset(0, -1).ClearContents
DoEvents
Loop
If pressdown = True Then
Call movedown 'Calls similar macro to moveright, but to movedown, hehe
End If
End Sub
Private Sub Form_KeyPress(Key As Integer)
Const down = "{DOWN}"
If Application.OnKey = down Then pressdown = True
End Sub
答案 0 :(得分:1)
您不能在任何随机位置拥有Form_KeyPress(Key As Integer)
。它是一个必须在用户表单中的事件处理程序。如果它在那里,你会得到一个编译时错误,因为你无法做If Application.OnKey = down
,无论这意味着什么。你正在逃避它,因为这个子从未输入,因此永远不会被编译。
话虽如此,你的做法是错误的 有一个循环可以使蛇在设定的方向上移动,并且有四个关键处理程序可以改变这个设定方向。
另请注意,直接循环不是一种好方法,因为它会导致Excel按键操作中出现问题。我建议你使用OnTime
作为主循环:
private move_where as string
Sub DemoOnKey()
Application.OnKey "{RIGHT}", "moveright"
Application.OnKey "{LEFT}", "moveleft"
Application.OnKey "{DOWN}", "movedown"
Application.OnKey "{UP}", "moveup"
End Sub
private Sub moveright()
move_where = "right"
end sub
private Sub moveleft()
move_where = "left"
end sub
private Sub movedown()
move_where = "down"
end sub
private Sub moveup()
move_where = "up"
end sub
Sub move()
select case move_where
case "right"
' Move right here
case "left"
' Move left here
case "down"
' Move down here
case "up"
' Move up here
end select
Application.OnTime DateAdd("s", 1, Now), "move"
End Sub