Delete row using UserForm - excel

I have built a simple UserForm with a Combobox to delete rows by name.
I have populated the Combobox rowsource using a macro to build a
named range called "Combo_List". I statically inserted that into the
rowsource attribute (meaning, I did not do that with code).
Also on the UserForm is a Checkbox that I want to use for confirmation purposes.
Once they select the username from the list, they need to put a check in the Checkbox and THEN they can click the Delete button.
I have no clue how to write the code that validates the Checkbox and then deletes the selected row.
If it helps, here's the code to build the named range and then show the UserForm:
Sub RecordDelete()
Dim LastRow As Long
ActiveSheet.Select
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
Range("B3:B" & LastRow).Name = "Combo_List"
frmDeleteData.Show
End Sub
The checkbox is just named 'checkbox1'. Any help?

One way to do this is
Set the default property for Enabled for your delete CommandButton to False in design mode
Add code to the CheckBox that enables the CommandButtonwhen the Checkbox is ticked
Add code to the delete CommandButton to delete the entire row
code
Private Sub CheckBox1_Click()
CommandButton1.Enabled = CheckBox1.Value
End Sub
Private Sub CommandButton1_Click()
Dim rng1 As Range
If Me.CheckBox1 Then
Set rng1 = Range("Combo_List").Find(Me.ComboBox1.Value, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
rng1.EntireRow.Delete
Else
MsgBox Me.ComboBox1.Value & "not found"
End If
Else
`redundant if button is disabled
MsgBox "Checkbox not checked!", vbCritical
End If
End Sub

Related

Vba to mark Check Box if specific cells contains specific imput

i need to create check box to be checked only if another specific cell contains specific input and unchecked if this input is not existing, noting that i tried below code
Private Sub Worksheet_Ca()
Dim DestS As Worksheet
Set DestS = ThisWorkbook.Worksheets("rest")
Dim DestSh As Range
Set DestSh = DestS.Range("B2")
If DestSh.Value = "Device" Then
DestS.CheckBoxes("Reset").Value = xlOn
Else
DestS.CheckBoxes("Reset").Value = xlOff
End If
End Sub
Also the check box i used is part of the forms toolbar not activeX and i changed the name of the check box to 'reset'
The error i got using debug is
method of checkbox of object _worksheet failed
Please, copy the next event code in the worksheet "rest" code module:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B2")) Is Nothing Then
If Target.value = "Device" Then
CheckBoxes("Reset").value = True
Else
CheckBoxes("Reset").value = False
End If
End If
End Sub
When you change the "B2" cell value in "Device", the check box will be checked. If you change its value in something else, the check box will be unchecked...
In order to copy the code in that sheet module, please activate sheet "rest" execute right click on the sheet name, choose View Code and copy the above code in the window which opens...

Excel VBA: Pass `Target` Variable from Click Event to Userform

I am building an Excel 2016 Userform using VBA and need to collect the row and column of the cell from which the form is opened. I open the form on a cell double click with Worksheet_BeforeDoubleClick and then initialize the Userform with UserForm_Initialize(). I would like to pass the Target of the double click event to UserForm_Initialize() but am not sure how to. This forum thread addresses this issue, but the provided solutions did not work for me.
Here is my Worksheet_BeforeDoubleClick:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Column = Target.Column
Row = Target.Row
'Find the last non-blank cell in column B(2)
lRow = Cells(Rows.Count, 2).End(xlDown).Row
'Find the last non-blank cell in row 2
lCol = Cells(2, Columns.Count).End(xlToRight).Column
If Not Intersect(Target, Range(Cells(3, 3), Cells(lRow, lCol))) Is Nothing Then
Cancel = True
EdgeEntryForm.Show
End If
End Sub
And my UserForm_Initialize():
Private Sub UserForm_Initialize()
Dim Column As Long, Row As Long 'I would like to fill these with the Target values
MsgBox ("Row is " & Row & " Column is " & Column)
'Description.Caption = "Fill out this form to define a network edge from " & Cells(2, Row).Value & " to " & Cells(Column, 2).Value
End Sub
As suggested in my comments, one way would be to just use the ActiveCell and assign that to a variable.
Alternatively, if you do want to pass it as a variable, you can do it with a bit of a workaround, by having a global variable to temporarly hold that information:
In your worksheet code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'.....
With UserForm1
Set .rngTarget = Target
.Show
End With
'.....
End Sub
In your userform:
Public rngTarget As Range
Private Sub UserForm_Activate()
'....
If Not rngTarget Is Nothing Then
MsgBox ("Row is " & rngTarget.Row & " Column is " & rngTarget.Column)
Else
MsgBox "something went wrong with assigning rngTarget variable"
End If
'....
End Sub
EDIT: I was trying initially to propose something similar to #MathieuGuindon's answer, but was failing due to my limited knowledge on the difference between initialise and activate (thanks Mathieu).
I've updated the answer to make use of the global variable at userform level, rather than use one from a module.
The form is shown modally, so ActiveCell isn't going to change on you, and should be safe to use in the form's code-behind.
The problem with that, is that you've now tied the form to ActiveSheet/ActiveCell, and now in order to test anything you need to Select or Activate a cell.
If the form code only needs to know about the cell's Address, then it shouldn't be given a Range (give it a Range and it can access any cell in any sheet in any workbook in the Application instance) - that's the principle of least knowledge at play. But this is obviously example code, so let's go with a Range:
Option Explicit
Private internalWorkingCell As Range
Public Property Get WorkingCell() As Range
Set WorkingCell = internalWorkingCell
End Property
Public Property Set WorkingCell(ByVal value As Range)
Set internalWorkingCell = value
End Property
Now your form code can use WorkingCell or internalWorkingCell to do its thing, and no global variable needs to float around;
With New UserForm1 ' Initialize handler runs here
Set .WorkingCell = Target
.Show ' Activate handler runs here
End With
The WorkingCell belongs to the form - it has no business being in global scope.
Careful with the Initialize handler in forms - especially when you use its default instance (i.e. when you don't New it up): you don't control when that handler runs, the VBA runtime does; UserForm_Initialize will run the first time the form instance is referenced (in your case, immediately before the .Show call), and then never again unless the instance is destroyed (clicking the red X button would do that).
A MsgBox call in the Initialize handler will run before the form is shown; you probably want to move that code to the Activate handler before it causes problems.

Fill ComboBox in UserForm with defined Range

In my UserForm is a ComboBox, this ComboBox shows a list with more than 100 values. If I start typing some letters into the ComboBox I want that the dropdown-list will automatically only shows the values which has the typed letters (this works fine so far). But if I choose one value the ComboBox will stay empty.
Here is my code for the ComboBox:
Private Sub ComboBox1_Change()
Worksheets("DataSheet").Range("B1").Value = dbCustomer.Value
dbCustomer.RowSource = "=ddCustomer" 'Named Range
End Sub
In my Worksheet "DataSheet" in column "D" I wrote the formula:
=IFERROR(INDEX(Customer;AGGREGAT(15;6;(ROW(Customer)-1)/(--(SEARCH($B$1;Customer)>0));ZEILE()-1);1);"")
The named range "ddCustomer" I saved with:
=DataSheet!$D$2:INDEX(DataSheet!$D$2:$D$105;COUNTIF(DataSheet!$D$2:$D$105;"?*"))
What do I have to change, that the value which I choose will shown in the ComboBox?
EDIT
Could find a solution, maybe it is not perfect but it works fine for me.
Private Sub dbCustomer_Change()
Dim customer As Object
Set customerValue = Worksheets("DataSheet").Range("C2:C479").Find(dbCustomer.Value, LookIn:=xlValues, LookAt:=xlWhole)
If customerValue Is Nothing Then
dbCustomer.Clear
GoTo FillDB
Else
Worksheets("DataSheet").Range("B1").Value = ""
Exit Sub
End If
FillDB:
Worksheets("DataSheet").Range("B1").Value = dbCustomer.Value
For Each customer In Worksheets("DataSheet").Range("D2:D479")
If customer <> "" Then
dbCustomer.AddItem customer.Value
End If
Next
End Sub

How to add a label and textbox based on combo box selection on a userform in excel

I am currently working on a userform to create an order for users at a company to send to my dept.
At the moment i have come to a standstill as i am struggling to work out the following.
I have a combobox which has a list of products our business offers. Based on the selection i want to be able to add labels and textbox which require the user to enter data for example.
If this selection in the combo box then
Enter name, date required, location of user etc.
Also this needs to be specific to the combobox selection.
Any help would be much appreciated :)
UPDATE
Apologies, as i did not have any code for that function I did not add any Here is the code i have.
Private Sub CommandButton1_Click()
Windows("RFS User Form Mock.xlsm").Visible = True
End Sub
Private Sub LegendDefinition_Change()
LegendDefinition.Locked = True
End Sub
Private Sub RequestList_Change()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Sheets("Definition").Cells(i, "A").Value = (Me.RequestList) Then
Me.DefinitionBox = Sheets("Definition").Cells(i, "B").Value
End If
Next
End Sub
Private Sub RequestList_DropButtonClick()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
If Me.RequestList.ListCount = 0 Then
For i = 2 To LastRow
Me.RequestList.AddItem Sheets("Definition").Cells(i, "A").Value
Next i
End If
End Sub
Sub UserForm_Initialize()
SiteList.List = Array("Birmingham", "Bristol", "Cardiff", "Chelmsford", "Edinburgh", "Fenchurch Street", "Glasgow", "Guernsey", "Halifax", "Homeworker", "Horsham", "Ipswich", "Jersey", "Leeds", "Leicester", "Lennox Wood", "Liverpool", "Manchester", "Peterborough", "Redhill", "Sunderland", "Madrid")
End Sub
Private Sub VLookUp_Change()
VLookUp.Locked = True
End Sub
When posting a question, you are expected to provide some code showing where you're standing trying to address the problem. Here's nevertheless a short demo that will give you a starting point.
Create a new UserForm and put a combobox, a label and a textbox on it; ensure they're named ComboBox1, Label1 and TextBox1, respectively.
Then, paste this code in the form's module:
Option Explicit
Private Sub ComboBox1_Change()
Dim bVisible As Boolean
'Only show the label and the textbox when the combo list index is 1, which corresponds to "Item 2".
'Note: bVisible = (ComboBox1.Text = "Item 2") would also work.
bVisible = (ComboBox1.ListIndex = 1)
Label1.Visible = bVisible
TextBox1.Visible = bVisible
End Sub
Private Sub UserForm_Layout()
'Populate the combo.
ComboBox1.AddItem "Item 1", 0
ComboBox1.AddItem "Item 2", 1
'Note: the code below could be removed by setting the corresponding
'design-time properties from the form designer.
ComboBox1.Style = fmStyleDropDownList
Label1.Visible = False
TextBox1.Visible = False
End Sub
Then press F5 to show the form. You'll notice that the label and textbox are only visible when the combo shows "Item 2". The visibility adjustment is performed within the ComboBox1_Change event handler.
If you plan on having numerous controls shown / hidden depending on your combo's value, you could group them into one or more Frame controls, and show / hide those frames instead.

Using VBA userform to select ranges on multiple sheets - sheet changes back to original activesheet

I have a userform which has multiple RefEdit controls. I need the user to select ranges from multiple sheets and the userform has to be complete before the rest of the code can run.
Issue: The activesheet is "Sheet1" when the userform is initiated. Each time I select a range on "Sheet2" and click into the next RefEdit the visible Excel sheet returns to "Sheet1". I'd like the sheet to remain on "Sheet2", since clicking between the sheets significantly increases the time it takes to select the data.
Because I need the userform to be completed before continuing with my code, using "vbModeless" doesn't appear to work.
I've tried to step through the userform events which appeared to be relevant but none were activated when I entered the RefEdit, selected the data, or left the RefEdit.
Thanks in advance for any help!
Edit: Using some input from the responses and doing some more research I think I've figured out the problem and a work around.
RefEdit events such as Change or Exit (I tried all of them I think) don't appear to trigger when a change occurs in the control. So I couldn't write code to manipulate the activesheet when I changed the control. A workaround found here: http://peltiertech.com/refedit-control-alternative/ uses a textbox and inputbox to simulate a RefEdit control and will actually trigger when changes are made! Code is below. To add other "RefEdit" controls you should repeat the code in the Userform_Initialize event for each control, then add another TextBox1_DropButtonClick and update TextBox1 to the name of the new control. In use when the control updates the workbook jumps to the previous activesheet and then returns the desired activesheet. Not as smooth as I'd like but much better than it was.
Code:
Private Sub CancelButton_Click()
Unload Me
End
End Sub
Private Sub OKButton_Click()
UserForm1.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
End
End Sub
Private Sub UserForm_Initialize()
Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End Sub
Private Sub TextBox1_DropButtonClick()
Dim ASheet As String ' Active sheet
Me.Hide
'Use input box to allow user to select a range
On Error Resume Next
Me.TextBox1.Value = Application.InputBox("Select the range containing your data", _
"Select Chart Data", Me.TextBox1.Text, Me.Left + 2, _
Me.Top - 86, , , 0)
On Error GoTo 0
'Check if there is a sheet name - if the range selected is on the activesheet the output of the inputbox doesn't have a sheet name.
If InStr(1, Me.TextBox1.Value, "!", vbTextCompare) > 0 Then ' there is a sheet name
ASheet = Replace(Split(Me.TextBox1.Value, "!")(0), "=", "") ' extract sheet name
Else ' there is no sheet name
Me.TextBox1.Value = "=" & ActiveSheet.Name & "!" & Replace(Me.TextBox1.Value, "=", "") ' add active sheet name to inputbox output
ASheet = ActiveSheet.Name
End If
Worksheets(ASheet).Activate ' set the active sheet
Me.Show
End Sub
Have you tried something as simple as:
Sheets("Sheet2").Select
somewhere in the beginning of your form code ?
Since you haven't posted your code, it's hard to provide a good answer.
Hope this helps a little :)
This form module worked for me.
Private Sub CommandButton1_Click() 'Cancel Button
Unload Me
End Sub
Private Sub CommandButton2_Click() 'GO Button
Dim newSheet As Worksheet
abc = Split(RefEdit1.Value, "!")
cbn = abc(0)
Unload Me
Set newSheet = Worksheets(abc(0))
newSheet.Activate
End Sub

Resources