Generate a random number between a to b - excel

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.

Related

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.

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

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: Multiple Userforms Referencing Same Code

I have a VBA code that takes user inputs (criteria) via a userform, creates a list of items that meet said criteria, and randomly outputs one of the list items via message box.
I want to create a second userform that will open after the above code completes, and have the userform display the random output.
I have a few questions regarding how this can be done.
I want to the second userform to contain a label, whose caption will reflect the random output.
I want the second userform to allow the user to re-execute the original code (ie. to change the random result)
Anyone have experience with this?
I'd use a Property procedure in the second form to get the random value.
As an example in a new blank workbook:
Insert a new module and paste in the code below. This code represents your code which outputs a random result.
Public Function RandomNumber() As Double
RandomNumber = Rnd(10)
End Function
Create a new userform (UserForm2), add a command button (CommandButton1) and a label (Label1). Add the below code to this form. I've put four procedures in there. MyProp sets the value of ThePassedNumber, UpdateLabel1 updates the value shown in the label, UserForm_Initialize executes when the form loads, CommandButton1_Click executes when you click the button.
Private ThePassedNumber As Double
Property Let MyProp(TheNumber As Double)
ThePassedNumber = TheNumber
UpdateLabel1
End Property
Private Sub CommandButton1_Click()
ThePassedNumber = RandomNumber
UpdateLabel1
End Sub
Private Sub UserForm_Initialize()
UpdateLabel1
End Sub
Private Sub UpdateLabel1()
Me.Label1.Caption = ThePassedNumber
End Sub
Add a second form (UserForm1) and add a command button (CommandButton1) and place this code within the form.
It will create a new instance of the userform, pass a random value to it and then display the form.
Private Sub CommandButton1_Click()
Dim frm2 As UserForm2
Set frm2 = New UserForm2
frm2.MyProp = RandomNumber
frm2.Show
End Sub
Now you just need to rewrite the RandomNumber function to return your list item rather than a number.
I imagine you just want to use an endless loop that the user breaks when canceled.
Something like this:
Sub MySub()
Dim myRandOutput As Single
Do
myRandOutput = myRand()
Loop While MsgBox(myRandOutput, vbRetryCancel) = vbRetry
End Sub
Function myRand() As Single
myRand = Rnd()
End Function

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.

VBA Excel: How can I store a real number but display a rounded number in a textbox?

I am calculating a bunch of values like density and volume. I show them on a form and when the user clicks "Update", I save that number to a worksheet.
There are a lot of numbers, so I want to neatly display the rounded version without losing the better precision number.
Like
Sub SetDensity()
dim rDensity as double
rDensity = 0.78022134
me.txtDensity = Format(rDensity,"0.00") ' user sees 0.78
End Sub
When data is finally written to worksheet, I want to be able to store the full precision like:
Sub UpdateWS()
Sheets(1).Range("A:A") = me.txtDensity ' put value 0.78022134 on worksheet
End Sub
Does the textbox have an alternate field where I can store the full number without displaying it, or do I need a hidden textbox for every real number that contains the full value?
Thanks
You could use the TextBox's Tag property to store the value. Here's a simple example:
Private Sub UserForm_Activate()
Me.TextBox1.Tag = 2.38232
Me.TextBox1.Value = Format(Me.TextBox1.Tag, "0.00")
Me.TextBox2.Tag = 4.99999
Me.TextBox2.Value = Format(Me.TextBox2.Tag, "0.00")
End Sub
Private Sub CommandButton1_Click()
MsgBox Me.TextBox1.Tag * Me.TextBox2.Tag
End Sub
What you ideally do in this situation is create an instance of a userform and pass the values into it as Properties, and then when the user clicks "OK" you get the computed value back out as another Form Property. Here's a post from my site, and one from Daily Dose of Excel, that give you the general idea. You could use these concepts and modify to work with textboxes.

Resources