0

如何通过按工作表上的按钮来调用此功能?我希望能够确保我的宏运行,目前它只有在我打开代码然后在最后一个结束子之后按 enter 时才会运行。

Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4




Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Key As Integer

If Target.Count > 1 Then Exit Sub

Key = GetKeyState(MOUSEEVENTF_LEFTDOWN)

If Key And 1 Then
If IsNumeric(Target.Value) Then
    Target.Value = Target.Value + 1
    Application.EnableEvents = False
        Target.Resize(1, 2).Select
    Application.EnableEvents = True
End If
Cancel = True
End If



End Sub
4

1 回答 1

0

如何通过按工作表上的按钮来调用此功能?

你没有。此方法与 Worksheet 更改事件紧密相关。

您应该做的是将此代码隔离到一个单独的子代码中,然后可以在Click工作表中按钮的方法中调用该代码。

Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4


Private Sub CommandButton1_Click()
myWorksheetChange Range("A1") 'or whatever range you want to call it using

end Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
myWorksheetChange Target

End Sub



Public Sub myWorksheetChange(ByVal Target as Range)

    Dim Key As Integer

    If Target.Count > 1 Then Exit Sub

    Key = GetKeyState(MOUSEEVENTF_LEFTDOWN)

    If Key And 1 Then
    If IsNumeric(Target.Value) Then
        Target.Value = Target.Value + 1
        Application.EnableEvents = False
            Target.Resize(1, 2).Select
        Application.EnableEvents = True
    End If
    Cancel = True
    End If

End Sub
于 2013-10-23T22:14:38.327 回答