How to call a function on ENTER key in Excel using vba - excel

Google should provide me with ample examples but none of them seem to work
What I want: Everytime the user presses, and then releases, the ENTER key, for my program to do do something (ie. create a MsgBox, or call function Foo). I would prefer this in the form of a MWE
What I have done: I have tried googling it but none of the examples are functional. They compile, but don't do anything. I have also made sure to save in a macro compatible Excel format.
What I am using: I am using Excel 2016, 64 bit with Office 365
EDIT: The user is entering this information into the worksheet. I want to intercept the user input and everytime they press ENTER, take the cursor/active cell down two rows, so there is an empty cell below every cell. If the user presses tab, I want to take the cursor/active cell right two columns, so there si an empty cell to the right of every cell.
EDIT 2: here is a MWE of what I have right now which should work, but which does nothing. I am adding this to the worksheet, and not as a module
Sub SomeActions()
MsgBox ("Hello")
End Sub
Private Sub Workbook_Open()
Application.OnKey "~", "SomeActions"
End Sub

First, make an callback Sub that performs the logic you need. Put it into a new code module (NOT into worksheet code):
Sub SomeActions()
...
End Sub
Then, subscribe to OnKey event, for example, when the user opens the workbook (this code goes into ThisWorkbook) module in VBA editor:
Private Sub Workbook_Open()
Application.OnKey "~", "SomeActions"
End Sub
"~" means Enter key. For numeric keypad key use "{ENTER}".

What I want: Everytime the user presses, and then releases, the ENTER key, for my program to do do something (ie. create a MsgBox, or call function Foo). I would prefer this in the form of a MWE
If I read this correctly, you want a blank row between every user inputted value doing down and a blank column between every user inputted value going right.
On the worksheet code sheet:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
Application.EnableEvents = False
Dim r As Long, c As Long
If Target.Row / 2 <> Int(Target.Row / 2) Then r = 1
If Target.Column / 2 <> Int(Target.Column / 2) Then c = 1
Target.Offset(r, c).Activate
Application.EnableEvents = True
End Sub
This occurs for all navigation. If you only want this to occur on input, modify to suit a Worksheet_Change event macro instead of a Worksheet_SelectionChange event macro.

Related

Change active sheet based on selected item from a dropdown list

I have an Excel WorkBook with several Sheets. I would like to be able to select from a drop down list in the "Home" Sheet and after selection is made, automatically switch to the proper Sheet and select a specific Cell.
It appeared to be easy, but I have failed time and again to make it work.
Here is an example of what I would like to do:
The only code that I managed to have a little success with is the following:
Private Sub Worksheet_Activate()
With Sheets("Home")
If Cells(6, 3).Value = "A" Then
Sheets("A").Select
ActiveSheet.Range("B7").Select
End If
End With
End Sub
The problem with it is that it will not check for the value until the user moves to another sheet. Then when it comes back, it will check for it, and will take it to the correct one, but the user will be stuck in a loop without being able to go back to "Home". (I know that it will only work on cell C6, but I just wanted to try if it worked before changing the Range)
You need the worksheet change event, rather than activate. Try this, in the Home sheet module.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$C$6" Then
Application.Goto Sheets(Target.Text).Range("B7")
End If
End Sub

Generate a random number between a to b

I have knowledge of the RANDBETWEEN() function inside the cells of Excel. This only returns one (1) value. I would like to assign this to a button to return a different value every time the button is hit.
I can create the button, I have the cell. How can I link the two?
Long story short, every time a button is clicked a cell (lets say cell a1) gets a different value between values a to b.
Try below
Private Sub CreateRandom()
'random number between 11 and 100
Debug.Print NewRandom(11, 100)
End Sub
Private Function NewRandom(ByVal FromLimit As Integer, ByVal ToLimit As Integer) As Integer
Randomize
randomNumber = Int((ToLimit - FromLimit) * Rnd) + FromLimit
NewRandom = randomNumber
End Function
Private Sub CommandButton1_Click()
'random number between 30 and 100
Sheets("Sheet2").Range("A1").Value = NewRandom(30, 100)
End Sub
MI Consol:
Sheets:
Private Sub CommandButton1_Click()
Call p
End Sub
Private Sub CommandButton3_Click()
Call save
End Sub
Private Sub CommandButton4_Click()
Call EMail
End Sub
Private Sub CommandButton5_Click()
Call iSMS
End Sub
Private Sub CommandButton6_Click()
Call continue
End Sub
Private Sub CommandButton7_Click()
Call Continue1
End Sub
If you're still using the RANDBETWEEN function and you just want it to generate a new value on command, just press F9 to force Excel to recalculate all formulas. RANDBETWEEN will then generate a new random number. (If it doesn't change value, it's just because it generated the same random number by chance. Keep pressing F9 to get new random numbers.)
Note that changing any formula on the spreadsheet will also cause the RANDBETWEEN function to generate a new value.
If you want a new random number to be generated ONLY when you command it to, then you do need to create a macro, which can be easily called through a button. I'm assuming you're not familiar with macros at all, so the following is a simple solution.
The following website explains how to create a simple button that will run a macro. (Note that this specific method only works with the ActiveX button, not the Forms button.)
https://www.tutorialspoint.com/vba/vba_excel_macros.htm
You will just need to replace the code in their example (MsgBox "Hi") with the following code:
Range("A1") = WorksheetFunction.RandBetween(a,b)
Replace a and b with the numbers you want to get a random number between. You can do this a few ways:
If you always want it between the same two numbers (e.g. 1 and 10), you can hard-code them into the macro:
Range("A1") = WorksheetFunction.RandBetween(1,10)
If you want it between two numbers recorded on the same spreadsheet (e.g. in cells B1 and B2), you can refer to the cells:
Range("A1") = WorksheetFunction.RandBetween(Range("B1"),Range("B2"))
Or you can ask for the numbers in popups:
a = InputBox("Enter a")
b = InputBox("Enter b")
Range("A1") = WorksheetFunction.RandBetween(a, b)
Note that the website misses a couple of important steps you must perform before the button will be able to used:
Close the VBA window (not actually necessary, but there's no need to leave it open)
Exit Design Mode. On the Developer tab in Excel, the Design Mode button should still be highlighted. Click it to un-highlight it. You can now click your button.
Note that if you want to change the code for the button again, you need to click Design Mode again to highlight it again, then you can double click the button to view the code again.

How to prevent clicking/selecting of odd rows and columns in Excel through VBA [duplicate]

Google should provide me with ample examples but none of them seem to work
What I want: Everytime the user presses, and then releases, the ENTER key, for my program to do do something (ie. create a MsgBox, or call function Foo). I would prefer this in the form of a MWE
What I have done: I have tried googling it but none of the examples are functional. They compile, but don't do anything. I have also made sure to save in a macro compatible Excel format.
What I am using: I am using Excel 2016, 64 bit with Office 365
EDIT: The user is entering this information into the worksheet. I want to intercept the user input and everytime they press ENTER, take the cursor/active cell down two rows, so there is an empty cell below every cell. If the user presses tab, I want to take the cursor/active cell right two columns, so there si an empty cell to the right of every cell.
EDIT 2: here is a MWE of what I have right now which should work, but which does nothing. I am adding this to the worksheet, and not as a module
Sub SomeActions()
MsgBox ("Hello")
End Sub
Private Sub Workbook_Open()
Application.OnKey "~", "SomeActions"
End Sub
First, make an callback Sub that performs the logic you need. Put it into a new code module (NOT into worksheet code):
Sub SomeActions()
...
End Sub
Then, subscribe to OnKey event, for example, when the user opens the workbook (this code goes into ThisWorkbook) module in VBA editor:
Private Sub Workbook_Open()
Application.OnKey "~", "SomeActions"
End Sub
"~" means Enter key. For numeric keypad key use "{ENTER}".
What I want: Everytime the user presses, and then releases, the ENTER key, for my program to do do something (ie. create a MsgBox, or call function Foo). I would prefer this in the form of a MWE
If I read this correctly, you want a blank row between every user inputted value doing down and a blank column between every user inputted value going right.
On the worksheet code sheet:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
Application.EnableEvents = False
Dim r As Long, c As Long
If Target.Row / 2 <> Int(Target.Row / 2) Then r = 1
If Target.Column / 2 <> Int(Target.Column / 2) Then c = 1
Target.Offset(r, c).Activate
Application.EnableEvents = True
End Sub
This occurs for all navigation. If you only want this to occur on input, modify to suit a Worksheet_Change event macro instead of a Worksheet_SelectionChange event macro.

VBA Activex button to activate specific keypress seq

While Navigating my sheet I use the F5+[enter] to navigate back to the cell that I hyperlinked from on a different sheet in the same workbook.
I have now made an Activex button to act as a back button but I need the script to make it do an F5+[enter] when clicked on.
I have lots of hyperlinks from different areas that go to one specific sheet and I basically want the Activex button to return the cursor back from whence it came.
Any help would be appreciated
Thank you
*****Sorry My fault I meant Active X Button*****
Edited and re tagged. Much appreciated
Since application.goto function stores the last reference as default you can simply bind a key for the following command
Application.Goto
This is not the perfect solution but it will do what you want. All you need to do is add this line to button_click.
As a general note, mimicking the actions of the keyboard through VBA involves using the Application.SendKeys command. In your specific case, the code would be:
Application.SendKeys "{F5}"
Application.Wait (Now + TimeValue("00:00:01"))
Application.SendKeys "~" 'The tilde is the Enter key
Generally, I prefer not to use this methodology. On my computer, for example, the third line of code runs before the first line has completed its action. In that case, I'm sitting with the Go To dialog box on my screen. That's why I separate the two lines with a call for the system to delay processing.
EDIT: (I think I cut off part of my original post)
In my opinion, your best bet is to allow Excel to handle the flow back to the hyperlink cells. The also opens up the possibility to move back beyond just the last cell. Below is a loose example of the code, which should be adapted.
In a module, enter the below code:
Public strLastSheet(1 To 10) As Worksheet
Public strLastRange(1 To 10) As Range
Public nLastCell As Integer
Public nCurrentIndex As Integer
Sub SelectLastHyperlinkedCellFoShizzle()
strLastSheet(nCurrentIndex).Activate
strLastRange(nCurrentIndex).Select
If nCurrentIndex <= 1 Then
'Do Nothing
Else
nCurrentIndex = nCurrentIndex - 1
End If
End Sub
In the ThisWorkbook code, enter the following:
Private Sub Workbook_Open()
nLastCell = 0
nCurrentIndex = 0
End Sub
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
nLastCell = nLastCell + 1
Set strLastSheet(nLastCell) = Sh
Set strLastRange(nLastCell) = Target.Parent
nCurrentIndex = nLastCell
End Sub
This is set to store the previous 10 hyperlink addresses. It should be further modified to disallow entries beyond 10 into the array, and perhaps shift the previous entries down the array.

Change Worksheet When a Cell Value and a Checkbox Change

I have a Workbook with multiple Sheets. I have a menu page (Worksheet) with multiple user choices (Enter a new order, update an order, etc.) Each choice has a check box beside it and depending on which check box is checked, cells F4:F21 change from 0 to 1 and, cell B1 changes to the name of the Worksheet where I want to go. I have the following VBA in the Main Menu worksheet but when I click a check box, nothing happens. Any ideas why?
CODE
Private Sub Worksheet_Activate()
ClearMenuForm
End Sub
Private Sub Worksheet_Change (ByVal Target As Range)
Dim sh As String
If Not Intersect(Target, Range("F4:F21")) Is Nothing Then
sh = Cells(1, "B").Value
Sheets(sh).Select
End If
End Sub
Clicking a check box does not activate the event Worksheet_Change (see this). That is why nothing happens.
Try changing one of the cells instead to see the effect.
What I think you want to do is assign an action to your Checkbox(es). You can do this in two ways:
Right clicking on the checkbox, and Assign Macro...
You have to create the associated macro, which will likely contain parts of the code that you already wrote, and/or calls to subs you have. You may bring the VBE (Alt+F11), insert a module in your VBA project, and write your Sub, e.g.,
Sub CheckBox1_Click()
MsgBox "Checkbox 1a has changed"
End Sub
Via VBA (e.g., this). With the sample code below, you would execute InitCBs, and that would associate CheckBox1Change with the checkbox (it actually assigns actions for both checkboxes in the figure; action for checkbox 2 is CheckBox2Change). You may also set InitCBs to be executed when opening the file.
Sub CheckBox1Change()
MsgBox "Checkbox 1b has changed"
End Sub
Sub InitCBs()
Dim cb As CheckBox
For Each cb In ActiveSheet.CheckBoxes
With cb
Dim action As String
'action = "CheckboxChange"
action = Replace(cb.Name, " ", "") & "Change"
.OnAction = action
End With
Next cb
End Sub
You've defined sh as a String. Since there is no sheet named "1", for example, your code will generate a "Subscript out of Range" runtime error. Try changing sh to a Long.
Dim sh As Long

Resources