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

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

Related

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

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

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.

Insert data in same row when a value in a cell is changed

I have code that retrieves information from SQL and VFP and populates a dropdown list in every cell in column "A" except A1 - this is a header.
I need to populate the "G" column on the row where the user selects the value from a dropdown in the "A" column.
I believe I need to be in Private Sub Worksheet_SelectionChange(ByVal Target As Range) which is in the sheet object.
Below is something similar to what I want to do.
If cell "a2".valuechanged then
Set "g2" = "8000"
End if
If cell "a3".valueChanged then
Set "g3" = "8000"
End if
The code above doesn't work, but I think it is easy to understand. I want to make this dynamic, so I don't have too many lines of code.
I have already explained about events and other things that you need to take care when working with Worksheet_Change HERE
You need to use Intersect with Worksheet_Change to check which cell the user made changes to.
Is this what you are trying?
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
'~~> Check if user has selected more than one cell
If Target.Cells.CountLarge > 1 Then Exit Sub
Application.EnableEvents = False
'~~> Check if the user made any changes in Col A
If Not Intersect(Target, Columns(1)) Is Nothing Then
'~~> Ensure it is not in row 1
If Target.Row > 1 Then
'~~> Write to relevant cell in Col G
Range("G" & Target.Row).Value = 8000
End If
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
Try this
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row > 1 And Target.Column <> 7 Then
Cells(Target.Row, "G").Value = 8000
End If
End Sub
If you only need it to fire on column A then
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row > 1 And Target.Column = 1 Then
Cells(Target.Row, "G").Value = 8000
End If
End Sub
can you not put an if statement in column G , as in
If (A1<>"", 8000,0)
Other wise something like this will get you going:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Column = 1 Then
If Target.Value2 <> "" Then
Target.Offset(0, 6) = "8000"
Else
Target.Offset(0, 6) = ""
End If
End If
On Error GoTo 0
End Sub
Thanks
Ross
I had a similar problem. I used Siddharth Rout's code. My modifications allow a user to paste a range of cells in column a (ex. A3:A6) and have multiple cells modified (ex. H3:H6).
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
'~~> Check if user has selected more than one cell
If Target.Cells.CountLarge < 1 Then Exit Sub
If Target.Cells.CountLarge > 500 Then Exit Sub
Debug.Print CStr(Target.Cells.CountLarge)
Application.EnableEvents = False
Dim the_row As Range
Dim the_range As Range
Set the_range = Target
'~~> Check if the user made any changes in Col A
If Not Intersect(the_range, Columns(1)) Is Nothing Then
For Each the_row In the_range.Rows
'~~> Ensure it is not in row 2
If the_row.Row > 2 Then
'~~> Write to relevant cell in Col H
Range("H" & the_row.Row).Value = Now
End If
Next
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub

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