Runtime error 1004 Method OnKey of object '_Application' failed - excel

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

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. learn.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

Related

UserForm to add from a selected cell from a TextBox value

I am trying to have a UserForm GUI so that we can add and subtract from inventory, I have got it so that I can select a worksheet and a row, but I am having trouble adding and subtracting part. Pretty new to VBA and I am not sure how to call that variable and modify it. Any help would be great!! Here is my code in the UserForm:
Option Explicit
Private Sub BTNadd_Click()
End Sub
Private Sub BTNDone_Click()
'This will save and close the GUI'
ThisWorkbook.Save
StgRmGUI.Hide
End Sub
Private Sub BTNrmv_Click()
End Sub
Private Sub ItmNmSlct_Change()
Dim actItm As String
End Sub
Private Sub ItmTypSlct_Change()
'This allows ItmTypSlct to show available wrkshts then will make item show in Item Name box'
With Worksheets(ItmTypSlct.Value)
ItmNmSlct.RowSource = Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp)).Address(, , , True)
End With
End Sub
Private Sub NumBox_Change()
Dim NewVal As Integer
NewVal = Val(NumBox.Text)
If NewVal >= SpBtnARNum.Min And _
NewVal <= SpBtnARNum.Max Then _
SpBtnARNum.Value = NewVal
End Sub
Private Sub SpBtnARNum_Change()
NumBox.Text = SpBtnARNum.Value
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Visible = xlSheetVisible Then
ItmTypSlct.AddItem ws.Name
End If
Next ws
End Sub
An simple example of updating the column B value by the amount in NumBox
Private Sub BTNadd_Click()
Dim r As Long, cell As Range
With ItmNmSlct
r = .ListIndex
If r < 0 Then Exit Sub
' select quatity cell and increment value
Set cell = Range(.RowSource).Cells(r + 1, 2)
cell.Value = cell.Value + NumBox.Value
End With
End Sub

How to combine multiple worksheet Change events Excel VBA

I need to combine the following 3 subroutines into a single worksheet change event but I am unsure how.
I have tried writing one sub in the worksheet editor and another in the workbook editor. However given that I have 3 subroutines all referring to the same worksheet, I am unsure how to combine them. Any help is greatly appreciated!
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D3:D100")) Is Nothing Then
Exit Sub
Else
Dim i As Integer
For i = 3 To 100
If Range("D" & i).Value = "Remote" Then
Range("O" & i).Value = "N/A"
Range("P" & i).Value = "N/A"
Range("Q" & i).Value = "N/A"
End If
Next i
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target,Range("H3:H100")) Is Nothing Then
Exit Sub
Else
Dim e As Integer
For e = 3 To 100
If Range("H" & e).Value = 1 Then
Range("I" & e).Value = "N/A"
End If
Next e
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target,Range("I3:I100")) Is Nothing Then
Exit Sub
Else
Dim e As Integer
For e = 3 To 100
If Range("I" & e).Value = 1 Then
Range("H" & e).Value = "N/A"
End If
Next e
End If
End Sub
Flip the logic.
If Intersect(Target, Range("D3:D100")) Is Nothing Then
Exit Sub
Else
...
End If
Change this to
If Not Intersect(Target, Range("D3:D100")) Is Nothing Then
' Remove Exit Sub
' Remove Else
...
End If
Do the same for the two other Intersect calls and then combine everything into one Worksheet_Change handler.
Most likely you want to disable events as well, to avoid re-triggering the event when writing to the sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo SafeExit
Application.EnableEvents = False
' Your three Intersect checks
SafeExit:
Application.EnableEvents = True
End Sub
try this. put this in the worksheet, not the workbook
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Integer
If Not Intersect(Target, Range("D3:D100")) Is Nothing Then
c = 1
Else
If Not Intersect(Target, Range("H3:H100")) Is Nothing Then
c = 2
Else
If Not Intersect(Target, Range("I3:I100")) Is Nothing Then
c = 3
End If
End If
End If
Select Case c
Case 1
' your stuff
Case 2
'your stuff
Case 3
'your stuff
Case Else
End Select
End Sub

How to trigger code if Enter key is pressed in a column

I'm trying to move to first cell of next row of column "A" in excel whenever enter key is pressed in Column "H". My code so far is below;
Private Sub move_to_next_row(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
ActiveCell.Offset(1, -7).Activate
End If
End Sub
There is no KeyDown event or something similar for worksheets. You can only check if a cell in column H was changed and then move to the first column in the next row.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Columns("H")) Is Nothing Then
Me.Cells(Target.Row + 1, "A").Select
End If
End Sub
Not For Points
Another way in case you want to trap the "Enter" key in Col H (irrespective of whether user made a change or not in column H)
Credits:
#Tom for Application.OnKey
#AsUsual for Worksheet_SelectionChange
Place this in the worksheet code area
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim wsName As String
wsName = ActiveSheet.Name
If ActiveCell.Column = 8 Then Application.OnKey "{Enter}", _
"'MoveCursor" & Chr(34) & wsName & Chr(34) & "'"
End Sub
Place this in the module.
Option Explicit
Sub MoveCursor(wsN As String)
If ActiveWorkbook.Name <> ThisWorkbook.Name Then GoTo CleanExit
If ActiveSheet.Name <> wsN Then GoTo CleanExit
Cells(ActiveCell.Row + 1, 1).Select
CleanExit:
'<~~ Reset the key to avoid undesirable sideeffects!
Application.OnKey "{Enter}"
End Sub
Try this (also gets triggered by the down arrow)
Option Explicit
Private col As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Target
If .Column = 8 And col = 8 Then
Cells(.Row, 1).Select
col = 0
Exit Sub
End If
col = .Column
End With
End Sub
In your ThisWorkbook Object place the following
Private Sub Workbook_Open()
Application.OnKey "~", "move_to_next_row"
End Sub
And then run using F5
Then in a normal module place
Sub move_to_next_row()
Dim SelectRng As Range
On Error Resume Next
If ActiveCell.Column = 8 Then
Set SelectRng = ActiveCell.Offset(1, -7)
Else
If Application.MoveAfterReturn Then
Select Case Application.MoveAfterReturnDirection
Case xlToLeft
Set SelectRng = ActiveCell.Offset(0, -1)
Case xlToRight
Set SelectRng = ActiveCell.Offset(0, 1)
Case xlUp
Set SelectRng = ActiveCell.Offset(-1, 0)
Case xlDown
Set SelectRng = ActiveCell.Offset(1, 0)
End Select
End If
End If
On Error GoTo 0
If Not SelectRng Is Nothing Then
SelectRng.Activate
End If
End Sub
Whenever you press the enter key move_to_next_row will be called. If the ActiveCell is in column H it will move the ActiveCell to Column A

Create button to copy row from Sheet 1 to Sheet 2

I have Worksheet 1, with columns A to D.
I would like to create a button executing row to be copied to Worksheet 2, as soon as cell C in Worksheet 1 is populated.
I have no experience in Excel at all, so far I found and altered this macro code for my needs:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 3 And Target.Cells.Count = 1 Then
Target.EntireRow.Copy _
Destination:=Sheets(2).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End If
End Sub
But when I try to create a button to execute this macro, it would never work. Could anyone help me solve this, please.
Is this what you are trying? Read more about Worksheet_Change HERE
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim lRow As Long
On Error GoTo Whoa
Application.EnableEvents = False
If Target.Cells.CountLarge > 1 Then Exit Sub
Set ws = ThisWorkbook.Sheets("Sheet2")
lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row + 1
If Not Intersect(Target, Columns(3)) Is Nothing Then _
Target.EntireRow.Copy Destination:=ws.Rows(lRow)
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
EDIT:
If the code still doesn't work then from the VBA Editor, press CTRL + G to bring up the immediate window and type this
Application.EnableEvents = True
and press ENTER key and now the code should work.

VBA Excel - Function Stuck

I am new ti VBA and i would like to perform a function as follows i hope someone could help me out
I need to set a macro that starts at Cell A2 when i click my function a dialog box appears which i can enter relevant information into and it inserts into the relevant cells
inserts data into 3 fields (B2, C2, D2)
then selects B3 where i can press my button again to do the same thins again
heres my code so far
Dim StartCell As Integer
Private Sub Cancel_Click()
Unload GarageDimensions
End Sub
Private Sub LengthBox_Change()
If LengthBox.Value >= 15 Then
MsgBox "Are you sure? You do realise it is just a garage!"
Exit Sub
End If
End Sub
Private Sub Submit_Click()
'This code tells the text entered into the job reference textbox to be inserted _
into the first cell in the job reference column.
StartCell = Cells(1, 2)
Sheets("Data").Activate
If IsBlankStartCell Then
ActiveCell(1, 1) = JobRef.Text
ActiveCell.Offset(0, 1).Select
ActiveCell(1, 1) = LengthBox.Value
ActiveCell.Offset(0, 1).Select
ActiveCell(1, 1) = ListBox1.Value
ActiveCell.Offset(0, 1).Select
ActiveCell(1, 1) = ListBox1.Value * LengthBox.Value
Else
Range("A1").End(xlDown).Offset(1, 0).Select
End If
Unload GarageDimensions
End Sub
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "2.2"
.AddItem "2.8"
.AddItem "3.4"
End With
ListBox1.ListIndex = 0
End Sub
Thanks for your answers in advance
Adam
You don't need the Private Sub LengthBox_Change() event. You can set the MAX characters of the TextBox LengthBox either in the Design Mode or in the UserForm_Initialize() event as I have done below.
Also if you hard-code the Startcell then every time you run the UserForm the data will start from A2 and if there is any data there, then that will be overwritten. Instead try and find the last available row where you can write.
BTW, is this what you are trying (UNTESTED)?
Option Explicit
Dim StartCell As Integer
Dim ws As Worksheet
Private Sub UserForm_Initialize()
Set ws = Sheets("Data")
With ListBox1
.AddItem "2.2"
.AddItem "2.8"
.AddItem "3.4"
.ListIndex = 0
End With
LengthBox.MaxLength = 14
End Sub
Private Sub Submit_Click()
With ws
'~~> Find the first empty row to write
StartCell = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A" & StartCell).Value = Val(Trim(ListBox1.Value)) _
* Val(Trim(LengthBox.Value))
.Range("B" & StartCell).Value = JobRef.Text
.Range("C" & StartCell).Value = LengthBox.Value
.Range("D" & StartCell).Value = ListBox1.Value
End With
Unload Me
End Sub
Private Sub Cancel_Click()
Set ws = Nothing
Unload Me
End Sub

Resources