如何禁用鼠标仅通过VBA单击特定的Excel工作表?

时间:2015-10-06 11:01:40

标签: excel vba mouse

我正在开发一个项目,其中要求不让用户使用鼠标从一个单元格移动到另一个单元格,它们只能通过Tab键移动。 所以,我不知道如何禁用鼠标点击特定的Excel工作表,并允许用户只使用Tab键。

提前致谢!

2 个答案:

答案 0 :(得分:2)

在这个答案中,我认为你的目标不是锁定单元格的编辑, 但仅限于禁用使用鼠标选择单元格。也就是说,仍允许用户编辑单元格,但她需要先使用Tab或箭头按钮选择它,然后按F2或键入来编辑它。

将以下代码添加到Worksheet的代码模块中:

Option Explicit
Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
' The keyword PtrSafe is needed only if you are working on a Win64 platform
' Remove it if you are using Win32

Private lastSelection As Range
Private Sub Worksheet_Activate()
   On Error Resume Next
   Set lastSelection = Selection.Cells(1)
   If Err.Number <> 0 Then Set lastSelection = Cells(1, 1)
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim e As Variant
    For Each e In Array(vbKeyUp, vbKeyDown, vbKeyLeft, vbKeyRight, vbKeyTab, vbKeyReturn, vbKeyHome, vbKeyEnd, vbKeyPageDown, vbKeyPageUp)
        If CBool(GetAsyncKeyState(e) And &H8000) Then 'You got here without using the mouse
            Set lastSelection = Target
            ' do other stuff if needed
            Exit Sub
        End If
    Next
   ' Selection was changed via mouse. Rollback
   If lastSelection Is Nothing Then Set lastSelection = Cells(1, 1)
   lastSelection.Activate
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As  Boolean)
    Cancel = True
End Sub

答案 1 :(得分:0)

几个选项

<强> 1。不保护工作表 - 强制所有点击回到单元格A1(在工作表的模块中)

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    With Target
        If .Column <> 1 Or .Row <> 1 Or .CountLarge > 1 Then Application.Undo
    End With
    Application.EnableEvents = True
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Application.EnableEvents = False
    With Target
        If .Column <> 1 Or .Row <> 1 Or .CountLarge > 1 Then Cells(1, 1).Select
    End With
    Application.EnableEvents = True
End Sub

<强> 2。保护工作表 - 不允许单元格导航

Private Sub Worksheet_Activate()
    Me.Protect
    Me.EnableSelection = xlNoSelection
End Sub