Is there a way to use an input value (textbox) of a userform as a variable for another userform? - vba

Ok so what I am trying to accomplish: I have one userform that asks how many new orders the user needs to process. I set the user input to a variable in this code (not sure if it even does anything).
Private Sub CommandButton1_Click()
UserForm2.Show
OrderNum.Text = NewOrders
'I changed the textbox name to OrderNum
End Sub
Then when UserForm2 pops up, I want to be able to input more data with more specific information about the orders. So if on Userform1 I entered in 3, I want to have to submit new data into UserForm2 3 different times. I tried using a For - Next loop (below) but it doesn't work. I'm not sure how (or if) I can store variables like that between Userforms.
Private Sub CommandButton1_Click()
Dim lRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Core Info")
OrderNum.Text = NewOrders
lRow = ws.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
For i = 1 To NewOrders
ws.Cells(lRow, 1).Value = TextBox1.Text
ws.Cells(lRow, 3).Value = TextBox2.Text
Next i
UserForm2.Hide
End Sub
The the second userform pops up as it should, but then nothing works after that. Can anyone tell me what I could do to fix this?
Note: I realize that those of the above start with CommandButton1 (default) but they are on different Userforms.

It will be helpful (and is good coding practice) to give your form controls more easily recognizable names, instead of the ambiguous CommandButton1 nomenclature. Revise CommandButton1's name on UserForm1 to Form1_SubmitButton. Then, use this code to handle the form submission.
Sub Form1_SubmitButton_Click()
' a textbox control named OrderNum on UserForm1 has captured the value
'Assign the value from the OrderNum textbox to a named variable in the worksheet
ActiveWorkbook.Names.Add "OrderNum", Me.OrderNum.Text
UserForm2.Show
End Sub
Then, in UserForm2 change the name of your command button to something like Form2_SubmitButton and use this code:
Sub Form2_SubmitButton_Click()
Dim orderNum as Long
orderNum = Replace(ActiveWorkbook.Names("OrderNum").Value,"=",vbNullString)
'the rest of your code goes here.
End Sub
So, what we have done above is to create a Name in the worksheet which contains the value you want to use on the several forms. You can always obtain this value by Replace(ActiveWorkbook.Names("OrderNum").Value,"=",vbNullString)
Alternatively, you could use a public variable in your code module.

Related

Call Userform based on Userform Value in cell

I have a table with the following values:
Now, I would like to call the Userform in column H based on the value in column G, but I can't work out how to call the Userform based on the cell value. The error occurs in line
form.Name = wsControls.Cells(loop2, 8).Value
Here is my code:
Sub Check_Scenarios()
Dim wsAbsatz As Worksheet
Dim wsControls As Worksheet
Dim wsData As Worksheet
Dim loop1 As Long
Dim loop2 As Long
Dim lngKW As Long
Dim form As UserForm
Set wsAbsatz = ThisWorkbook.Worksheets("Production")
Set wsData = ThisWorkbook.Worksheets("Data")
Set wsControls = ThisWorkbook.Worksheets("Controls")
lngKW = wsControls.Cells(1, 2).Value + 2
If lngKW = 3 Then
Exit Sub
End If
For loop1 = wsControls.Cells(10, 2).Value To wsControls.Cells(19, 2).Value Step 10
If wsData.Cells(loop1 + 3, lngKW).Value <> "" Then
MsgBox (wsData.Cells(loop1 + 3, lngKW).Value)
For loop2 = 2 To 16
If wsData.Cells(loop1 + 3, lngKW).Value = wsControls.Cells(loop2, 7).Value Then
form.Name = wsControls.Cells(loop2, 8).Value 'error occurs here
form.Show
End If
Next loop2
End If
Next loop1
End Sub
Project:
Many thanks for your help!
You are trying to assign a Name to a blueprint. These are two errors.
You have to initialize your blueprint as something. Like this:
Dim form As New UserForm
Then, most probably your UserForm does not have a property called Name. It is called Caption. Thus it is like this:
Sub TestMe()
Dim uf As New UserForm1 'judging from your screenshot
uf.Caption = "Testing"
uf.Show
End Sub
Disclaimer:
There is a better way to work with UserForms, not abusing the blueprint, although almost every VBA book shows this UserForm.Show method (in fact every single one I have read so far).
If you have the time and the OOP knowledge implement the ideas from here - or from my interpretation of the ideas. There was also a documentation article about it in StackOverflow, but it was deleted with the whole documentation idea.
You don't "call" a userform. You instantiate it, and then you Show it.
UserForm is the "base class" from which all userforms are derived. See there is inheritance in VBA, only not with custom classes.
So you have a UserForm2 class, a UserForm3 class, a UserForm4 class, and so on.
These classes need to be instantiated before they can be used.
Dim theForm As UserForm
Set theForm = New UserForm2
theForm.Show
Set theForm = New UserForm3
theForm.Show
'...
So what you need is a way to parameterize this Set theForm = New ????? part.
And you can't. Because whatever you're going to do, the contents of a cell is going to be a string, and there's no way you can get an instance of a UserForm3 out of a String that says "UserForm3".
Make a factory function that does the translation:
Public Function CreateForm(ByVal formName As String) As UserForm
Select Case formName
Case "UserForm1"
Set CreateForm = New UserForm1
Case "UserForm2"
Set CreateForm = New UserForm2
Case "UserForm3"
Set CreateForm = New UserForm3
'...
End Select
End Function
And then call that function to get your form object:
Set form = CreateForm(wsControls.Cells(loop2, 8).Value)
If Not form Is Nothing Then form.Show

VBA: ComboBox only showing one item after Workbook_Open event

I am attempting to have a Workbook_Open event populate a controls ComboBox
so that when the user goes to the Worksheet("Benchmarking"), they have a pre-populated list to choose from that includes all the items in the array datesArr.
The problem i am having is, upon opening the spreadsheet and navigating to the Worksheet("Benchmarking"), i am only seeing one item in the drop down list:
If i select that item then the list actually populates:
Desired result:
I want the full list to be available from the first time the user tries to make a selection not just after the ComboBox1_Change event is fired.
Having reviewed numerous post e.g. Sometimes the ActiveX Combobox only shows one row, why? , Populating Combo Box on WorkBook Open I have tried several different approaches including the following in the Workbook_Open event code:
.ListFillRange = "DropDownDates"
.List = DateArrToStrAr
I have also looped the array adding the items to ComboBox1. Each time i get the same 1 visible item in drop down result.
Is someone able to tell me where i am going wrong please?
My current code is
1) ThisWorkbook
Private Sub Workbook_Open()
With Worksheets("Benchmarking").OLEObjects("ComboBox1").Object
.Clear
.List = DateArrToStrArr '
End With
End Sub
2) Worksheet("Benchmarking"):
Private Sub ComboBox1_Change() 'QH 2/11/17
Dim datesArr() As String
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Lkup")
datesArr = DateArrToStrArr 'function that reads a named range of dates and converts to string to avoid dd/mm becoming mm/dd
If ComboBox1.Value = vbNullString Then ComboBox1.Value = "01/04/2016"
ComboBox1.List = datesArr
'.....other code
End Sub
Notes:
The array datesArr is populated by the function DateArrToStrArr() which reads in a named range of dates "DropDownDates" (workbook scope) and converts them to a string array. This is then assigned to the ComboBox.
DropDownDates is a dynamic named range with formula =OFFSET(Lkup!$F$16,,,Lkup!$M$12,)
Set-up: Excel 2016 64 bit Windows.
Thanks to #CLR for making me think about recalcs. I decided to hack my way around this with the following:
I have added in Worksheet("Benchmarking") a Worksheet_Activate event and removed the Workbook_Open code. This seems to do the trick
Private Sub Worksheet_Activate()
' ComboBox1.Clear
ComboBox1.List = DateArrToStrArr
End Sub

VBA with if case for checkbox in excel

I am having an userform where I have 8 Checkboxes in it.
Each checkbox is assigned to an call function called autofilter.
I would like to have an vba,in such a way that more than one Checkbox is used, then it should Display the result of selected Checkbox.
How can I achieve in VBA. I am struck how i should proceed with this Problem.
Expecting an help from Forum.
This is my autofilter program
Sub autofilter()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:AFU" & wslr)
myfilt.autofilter Field:=12, Criteria1:= _
"USA"
End Sub
similarly, i have them for other Locations as well till autofilter7.
Right now, i have the code working in such a way that, if check box 1 is true it calls autofilter1.
I would like to have a VBA, in such a way that, when i select 1 or more checkboxes, it should call their autofilter function together. How can i achieve this ?
[![I have userform with Checkboxes designed like this.in the command button i have the following code,
If CheckBox1.Value = True Then
Call autofilter
End If
similarly, I have it same for other checkboxes.
]1]1
Difficult to answer without all the exact details, but I think you are looking for something like:
In the command button _Click sub code, you should have this:
Edited : notice Dim i as String at the top.
Dim formControl As Control
Dim i As String
'loop through every control in the userform
For Each formControl In Me.Controls
'Test if the control is a checkbox
If LCase(TypeName(formControl)) = "checkbox" Then
If formControl.Value = True Then
'The below is very crude and you should find a better way of getting parameter from checkbox
'The below also assumes you use ONE filterFunction that takes a parameter
'You need to get the number from the checkbox, so take the number from the name of the checkbox
i = Right(formControl.Name, 1) - 1
'myFilterFunction i (Use this only if you have parameterised your function)
'change i to empty string if it was 0.
i = IIf(i = 0, "", i)
'This calls a function represented by the string
Application.Run "myFilterFunction" & i
End If
End If
Next formControl
At the moment, the away you've describe it, the code should work. Replace the name of the function with the name of your autofilter function....

Using relative references to reuse a macro for a control

I'm trying to write an Excel 2007 macro for a coworker, but my VBA skills are pretty basic (pardon the pun). Essentially, what needs to happen is, when a checkbox is clicked, the neighboring cell to the right is filled with the username of the person logged in.
So far, here's the code I've come up with that allows me to do that:
Sub CheckBox1_Click()
Range("J4").Activate
If ActiveCell.Offset(0, 18).Value = True Then
ActiveCell.Offset(0, 1).Value = Environ("UserName")
Else
ActiveCell.Offset(0, 1).Clear
End If
End Sub
Just for the sake of reference, that "ActiveCell.Offset(0,18)" refers to a cell that is linked to the checkbox in question and contains its true/false value.
(EDIT: Also, the reason cell J4 is activated is because in this case, it's the cell containing the ActiveX checkbox)
That works perfectly, but that's not my problem. My problem is this: there are 49 more checkboxes in that row, and three more rows on this sheet, and 45 more sheets in this book. I do NOT want to have to copy paste the same code into a unique macro just to change the active cell. More importantly, as a good programmer, I shouldn't be repeating code like that. How should I write this so that I don't have to refer to a distinct cell every time?
EDIT 2: Holy smokes, Lance just helped me realize I was mistaken. The sheet uses form controls, not ActiveX controls. Greatly sorry, everyone.
While this is easy to do with a Sheet object, it's pretty hard to do with an ActiveX Control object. You can't self-reference the name of an ActiveX Control in its event, unless it's passed to it, and you also can't reference the name of the event subroutine to extract the name, and you can't reference the name of the routine that called a routine.
I also attempted to trigger off of the Worksheet Change and SelectionChange events, but those don't trigger off of a checkbox change, even if it has a LinkedCell that changes
What I finally came up with was the somewhat generic wrapper for the click event, that you'll have to modify the string to match the Checkbox name:
Private Sub CheckBox1_Click()
NameCopy Me, "CheckBox1"
End Sub
and then a Namecopy function that sets the cell -7 to the left of the LinkedCell to the name value.
Public Sub NameCopy(wsheet As Worksheet, cname As String)
If wsheet.OLEObjects(cname).Object.Value = True Then
Range(wsheet.OLEObjects(cname).LinkedCell).Offset(0, -7).Value = Environ("UserName")
End If
End Sub
It's easier with a Forms checkbox, you can use this Macro for all your checkboxes. Just remember to set the Macro to this:
Public Sub NameCopy()
Dim shp As Shape
Set shp = ActiveSheet.Shapes(Application.Caller)
If shp.ControlFormat.Value = xlOn Then
ActiveSheet.Range(shp.ControlFormat.LinkedCell).Offset(0, -7).Value = Environ("UserName")
End If
End Sub
Since you are using form controls, this is really easy. You can use Application.Caller to have the code access the clicked checkbox, and then use it's TopLeftCell property to get where the checkbox is located, and then you can perform whatever operation you want. In your case, something like this I'm guessing:
Sub Checkbox_Click()
With ActiveSheet.CheckBoxes(Application.Caller)
If .Value = 1 Then 'Checkbox is checked
.TopLeftCell.Offset(, 1).Value = Environ("UserName")
Else
.TopLeftCell.Offset(, 1).ClearContents
End If
End With
End Sub

Open Website in excel using ActiveWorkbook.FollowHyperlink

So, this is basically what I'm trying to do. I have a column of employee #'s in a file that's generated from MSSQL. I want to create a function in a cell where the URL would be, http://www.someplace.com/employee.php?ID=Employee#FromCell
So far all of the examples that I've found aren't detailed enough for me to figure out what to do with it. I know this isn't correct, but this is what I ended up with so far
Function openurl(strSKU As String)
ActiveWorkbook.FollowHyperlink Address:="http://www.someplace.com/employee.php?ID=?strSKU=" & strSKU, NewWindow:=True
End Function
I think I'm mixing up methods with functions but I'm not sure where to go with it. I basically want to add it in as a function to make it easier to insert into the column.
I see someone provided you with a work-around for accomplishing this, but I'll give you the method you were asking for (just in case). FYI the intellisense sucks in VBA when referencing OLE objects (i.e., some methods may not appear to belong to the button objects, but they do).
The script below will create the buttons for you automatically, and will send the user to the site you specified when clicked. **I included notes which explain what each line does.
This creates the buttons in columns B and gets the URL parameter from column A:
Sub CreateButtons()
Dim btn As Button 'Create a variable for our button
Application.ScreenUpdating = False 'Speed up the process by disabling ScreenUpdating
ActiveSheet.Buttons.Delete 'Delete existing buttons.
Dim Report As Worksheet 'Create our worksheet variable.
Set Report = Excel.ActiveSheet 'Set our worksheet to the worksheet variable.
Dim t As Range 'Create a variable for the cells we will reference.
For i = 1 To Report.UsedRange.Rows.Count 'This will loop through each row in the used range of our worksheet.
If Report.Cells(i, 1).Value <> "" Then 'If the value of the first cell is not empty, then do the following...
Set t = Report.Range(Cells(i, 2), Cells(i, 2)) 'Assign the cell in the second column of the current row to the cell variable.
Set btn = Report.Buttons.Add(t.Left, t.Top, t.Width, t.Height) 'Create a button and place it in the cell in the second column.
With btn
.OnAction = "openurl" 'Set the button to trigger the openurl sub-routine when it is clicked.
.Caption = Report.Cells(i, 1).Value 'Set the caption of the button to equal the value of the cell in the first column.
.Name = i 'Set the name of the button to equal the row on which it resides. This name will be used in the openurl sub; So don't change it.
End With
End If
Next i
End Sub
This is the macro performed when the user clicks a button:
Sub openurl()
Dim Report As Worksheet 'Create a variable for the worksheet
Set Report = Excel.ActiveSheet 'Assign the worksheet to our variable
Dim i As Integer 'Create a variable for our row number
i = Application.Caller 'Assign name of the button to our row number.
Dim address As String 'Create a variable for our address
address = "http://www.someplace.com/employee.php?ID=?strSKU=" & Report.Cells(i, 1).Value 'Assign the URL to our address variable.
ActiveWorkbook.FollowHyperlink address:=address, NewWindow:=True 'Send the user to the URL you specified (with the URL parameter at the end).
End Sub
BONUS INFO:
Follow the next step to have the entire process done for you automatically:
When you say the current data is populated from a MSSQL database, you probably mean you are pulling the data into Excel using another VBA sub or function. If so, then if you place a script to call the "CreateButtons()" subroutine after the script that pulls the data, this entire process will be done for you automagically. Example:
Sub getEmployeeData() 'This represents your sub that pulls your data from MSSQL
'================================================================
'This represents your script to get your information into Excel.
'================================================================
Call CreateButtons 'This runs the CreateButtons() subroutine.
End Sub
Enjoy!
You can do this without VBA. You can use a formula.
=Hyperlink("http://www.someplace.com/employee.php?ID="&A1,A1)
Where A1 would have the employee ID.
Check out this post I made about creating hyperlinks from External Data:
http://www.spreadsheetsmadeeasy.com/creating-hyperlinks-with-external-data/
Scroll down to the "Add Hyperlinks" section for more info.