'Runtime error 1004 Method OnKey of object '_Application' failed
the following code causes
runtime error '1004' Method OnKey of object '_Application' failed! Any suggestions?
Sub MyAchieve()
Dim col As Integer
Dim row As Integer
col = activeCell.column
row = activeCell.row
col = col + 1
'Range(Cells(row, col), Cells(row, col)).Select
Cells(row, col).Select
End Sub
Private Sub Worksheet_Activate()
Dim activeCell As Range
Set activeCell = Selection
If activeCell.column >= 1 And activeCell.column <= 10 Then
Call Application.OnKey("ENTER", "MyAchieve")
End If
End Sub
I hoped this link ( [https://stackoverflow.com/questions/62880064/run-time-error-1004-method-onkey-of-object-application-failed][1] )was helpful, but it is the Application.OnKey("ENTER", "..."), which fails.
The following is the improved code, which uses a valid key (RETURN instead of ENTER)
Option Explicit
Sub getDateTime()
Dim EditDate As Date
Dim rng As Range
Set rng = Selection
rng.Value = Format(Now(), "dd/mm/yyyy hh:mm")
getNextCell
Exit Sub
error_handler:
MsgBox "getDateTime() " & Err.Number
Resume Next
End Sub
Sub getNextCell()
activeCell.Offset(0, 1).Activate
End Sub
Private Sub Worksheet_Activate()
Dim activeCell As Range
Set activeCell = Selection
Application.OnKey "{RETURN}", Cells(activeCell.row, activeCell.column + 1).Select
End Sub
Private Sub Workbook_Open()
Application.OnKey "{RETURN}", Cells(activeCell.row, activeCell.column + 1).Select
End Sub
Private Sub Worksheet_Deactivate()
Application.OnKey "{RETURN}"
End Sub
Solution 1:[1]
This was the correct answer. The link showed that it was {RETURN} I needed to code. Thank you braX:
I've never tried it, but it looks like ENTER is not a valid key. docs.microsoft.com/en-us/office/vba/api/excel.application.onkey - Maybe you wanted {ENTER} or ~? – braX
This is the corrected code. The error I now get is something like this: "Cannot run the macro 'name of my macro'. The macro may not be available in the workbook or all macros may be disabled." So thank you. I got all the help I asked for.
Option Explicit
Sub getDateTime()
Dim EditDate As Date
Dim rng As Range
Set rng = Selection
rng.Value = Format(Now(), "dd/mm/yyyy hh:mm")
getNextCell
Exit Sub
error_handler:
MsgBox "getDateTime() " & Err.Number
Resume Next
End Sub
Sub getNextCell()
activeCell.Offset(0, 1).Activate
End Sub
Private Sub Worksheet_Activate()
Dim activeCell As Range
Set activeCell = Selection
Application.OnKey "{RETURN}", Cells(activeCell.row, activeCell.column + 1).Select
End Sub
Private Sub Workbook_Open()
Application.OnKey "{RETURN}", Cells(activeCell.row, activeCell.column + 1).Select
End Sub
Private Sub Worksheet_Deactivate()
Application.OnKey "{RETURN}"
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Michaelinscarbororough |