Deleting a row if row selected - excel

How do you make a macro, which deletes a row if a row is selected, and otherwise prompts up an message box? I made a code like this but it always skips the first if statement and goes on to the next one.
Sub DeleteRow()
If ActiveCell.Row = True Then
Selection.EntireRow.Delete
Else: MsgBox "Choose a row first", vbOKOnly, "Delete a row"
End If
End Sub

You may try below sub
Sub DeleteRow()
If ActiveCell.Row = Selection.Row Then
Selection.EntireRow.Delete
Else: MsgBox "Choose a row first", vbOKOnly, "Delete a row"
End If
End Sub
Basically you can just run below single line to delete selected row.
Selection.EntireRow.Delete
This should also work
ActiveCell.EntireRow.Delete

Any time you want code to run when you do something to a worksheet, consider using the Worksheet subroutines.
The one you are interested in is the Worksheet_SelectionChange. The Worksheet subroutines (such as the Worksheet_SelectionChange are always stored in the code for that Sheet.) Here are a list of events that the Worksheet has.
Let's break your problem down:
When the user selects something, identify what they have selected
If the user has selected an entire row, do something OR
If the user has selected a single cell, do something else OR
If the user has selected anything else, ignore
The Worksheet_SelectionChange takes one parameter: Target, which is the selection that the user made.
Below is the code for deleting a row if it is selected. This should be enough for you to move in the right direction.
Again, the big take away: when responding to user input, always consider the built-in Worksheet subroutines.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Purpose:
' Delete a row if it is selected
' Check if a row was selected
Dim Address As String
Address = Target.Address
Address = Replace(Address, "$", "")
' Rows and columns have the form #:# when selected
' Where # is either the column letter OR the row number
If InStr(Address, ":") Then
' Since a : was in the address, an entire row or column was selected
' Was a column or row selected?
' Check if the members of AddressArray are numbers
Dim AddressArray As Variant
AddressArray = Split(Address, ":")
If IsNumeric(AddressArray(0)) And IsNumeric(AddressArray(1)) Then
' Both members of the array were numbers, so a row was selected
' Delete the row
Target.Delete
End If
End If
End Sub

I would go with this approach:
If Selection.Address = Selection.Cells(1).EntireRow.Address Then

Related

How to detect user selecting an entire row and distinguish if multiple rows are selected?

How do I detect if the user selected an entire row on the worksheet?
I would like to return which row is selected so I can automate routines - such as copying the data associated with that row.
I want the automation to be applicable to any one row and not multiple rows.
Put this in the code of the worksheet you want it to run on.
You can also check the 'address' property to determine where the selection is. This isn't a full answer, but it should get you started.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim bEntireRow As Boolean
With Target
bEntireRow = .Address = .EntireRow.Address
End With
If bEntireRow = True Then
MsgBox (Target.Rows.Count & " Rows Selected")
End If
End Sub

Make cursor jump to same row, different column when pressing Enter, with other specific requirements

I've had a look about and whilst I've found some similar threads (with varying degrees of relevancy/usefulness), none of them covered my exact situation.
I want to use a sheet in my workbook as a form where I input one type of data in one column and press enter, and then jump to another column on the same row to input a second type of data.
My sheet has an "Item Number" column and a "Count" column with several columns in between them.
What I'm trying to achieve is:
Type data into a cell in the "Item Number" column and press Enter.
The cursor appears on the same row, several columns to the right in the "Count" column.
I want this only to occur when pressing Enter after entering data into blank cells only
in the "Item Number" column. Pressing Enter in any other column should just allow the cursor to behave as it would otherwise.
At the moment I have the code
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("A100") = ActiveCell.Address
Cells(Application.ActiveCell.Row, 11).Select
End Sub
The first line (beginning with "Range") allows me to see the active cell address in cell A100. This works along with some other code that lets me colour fill the active cell in that worksheet so I can see things a bit better when the spreadsheet gets busy.
The second line (beginning with "Cells") is the code that is supposed to make the cursor jump over to the "Count" column after pressing Enter in the "Item Number" column.
Now, this all works fine except for one major drawback.....
When clicking on a cell in the "Item Number" column, the cursor is immediately moved to the "Count" column before I'm able to enter any data, let alone hit the Enter key.
What am I doing wrong?
and
How do I go about ensuring this only happens when pressing Enter after entering data into a blank cell in the "Item Number" column?
I hope this makes sense, reading so much about code has got me cross eyed.
Cheers
you should combine Worksheet_Change() and Worksheet_SelectionChange() events and use a sheet scoped variable to check for empty cells being changed
Option Explicit
Dim emptyCell As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub ' don't bother nulticell selections
If Cells(1, Target.Column).Value <> "Item Number" Then Exit Sub ' don't bother selections outside "Item Number" column
If emptyCell And Not IsEmpty(Target.Value) Then Cells(Target.Row, Range("A1", Cells(1, Columns.Count).End(xlToLeft)).Find(what:="Count", LookIn:=xlValues, lookat:=xlWhole).Column).Select ' if current cell was empty and now it is not then skip to "Count" column same row
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
emptyCell = IsEmpty(Target.Value) ' store the info about current selection being empty
End Sub
Please try the Change event. The code below should do what you want. It could be expanded to respond (differently) to changes in other columns.
Private Sub Worksheet_Change(ByVal Target As Range)
Const TriggerColumn As Long = 3 ' modify as required
Const NextColumn As Long = 11 ' modify as required
Dim Rng As Range
' don't take action if more than 1 cell was changed
If Target.Cells.CountLarge > 1 Then Exit Sub
' don't include the caption row in ther ange
' find the last used row in a column filled BEFORE Triggercolumn
Set Rng = Range(Cells(2, TriggerColumn), Cells(Rows.Count, "A").End(xlUp))
' take action only if the changed cell is within Rng
If Not Application.Intersect(Target, Rng) Is Nothing Then
' skip if the change resulted in a blank cell
With Target
If Len(.Value) Then
Cells(.Row, NextColumn).Select
Else
' prevent the next action from triggering this function
Application.EnableEvents = False
' delete contents of the next cell
Cells(.Row, NextColumn).ClearContents
Application.EnableEvents = True
End If
End With
End If
End Sub

delete a line or item selected on listbox of userform

I have a userform where I can enter some information, but I want also to give the user the possibility to delete the data that he entered by selecting it from listbox and then click on delete and they need to put a password. Unfortunately, I tried this code but it's doesn't work.
Private Sub delete_Click()
Dim i As Integer
For i = 1 To Range("A65656").End(xlUp).Row
If lstdiplay.Selected(i) Then
Rows(i + 1).Selected
Rows(i).Select
Selection.delete
End If
Next i
End Sub
When I select for example XOXO like the picture, and click on DELETE, i want to delete the entire information about XOXO, does mean delete XOXO and SA and his number phone etc.....and yes I have the same data on worksheet and After deleting data cells I want to remain blank
Private Sub delete_Click()
Const listStart As Long = 3 'Your listbox keeps the rows starting with row 3
Dim sh As Worksheet
Set sh = ActiveSheet 'better use your worksheet name here...
If Not Me.lstdiplay.ListIndex = -1 Then
Me.lstdiplay.RemoveItem Me.lstdiplay.ListIndex
sh.Rows(Me.lstdiplay.ListIndex + listStart).Delete
Else
MsgBox "You must have a listbox selected row!", vbInformation, "No row selected"
End If
End Sub
It removes the selected listbox row and deletes the equivalent sheet row. If the listbox has been loaded starting from row 3 inclusive. Otherwise, you should adapt the `listStart ' constant value...
It also warns in case of selection missing.

Ensure rows are fully complete before new rows of data can be entered

I am looking to restrict users in excel of adding data to new rows in a table unless all data has been entered in the previous row, can someone help? I currently have conditional formatting that highlights any row that has missing data, but I wanted to take it beyond this.
I see no easy way to prevent data entry on a new row.
However, you could use the Worksheet_Change event to test for complete entry, and undo the new data entry if the previous rows is incomplete.
Something like this
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lo As ListObject
Dim lr As ListRow
' Get reference to the first or only Table in the worksheet
Set lo = Me.ListObjects(1)
' If the change was not in the Table, there is nothing to do
If Application.Intersect(Target, lo.DataBodyRange) Is Nothing Then Exit Sub
' If there is only one row in the Table, there is nothing to do
If lo.ListRows.Count <= 1 Then Exit Sub
' Count the number of entries in the second last row
' if its less than the number of columns, that row is incomplete
If Application.CountA(lo.ListRows(lo.ListRows.Count - 1).Range) _
<> lo.ListColumns.Count Then
' Delete the last (newly created) row
lo.ListRows(lo.ListRows.Count).Delete
lo.ListRows(lo.ListRows.Count).Range.SpecialCells(xlCellTypeBlanks).Select
MsgBox "Please enter complete data before starting a new row!", _
vbOKOnly + vbError, "Undoing last data entry"
End If
End Sub

Excel tab to new line after certain amount of columns

I am wanting to set up an excel spreadsheet for data entry with a barcode scanner.
The barcode scanner sends the barcode then a tab OR an enter key depending how its programmed.
Basically I want to set up an excel sheet that we can scan 6 barcodes for each item, with the scanner tabbing to the next column each time, then when it reaches the 6th column the next tab will make it move to a new line for the next product.
I hope this makes sense. It can be done in MS word... e.g if you create a table with 6 columns and push tab 7 times it will move to the next row.
I am wanting to do this in Excel.
Thank you
The TAB or ENTER keys already trigger the SelectionChange event.
So, this might be a little tidier way of doing the same thing if you don't for some other reaason need to use the Change event instead of the SelectionChange event.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rngLastColumn As Range
'Note: The {Tab} or {Enter} key triggers selectionChange event.'
' Modify the address of rngLastColumn as needed. It should be one column beyond
' the last column of your inputs, so if input use columns A:F, then it should
' be Range("G:G").
Set rngLastColumn = Range("G:G")
If Not Intersect(Target, rngValidColumns.Columns(7)) Is Nothing Then
'Insert a new row:'
Target.EntireRow.Offset(1, 0).Insert
'Select the first cell in the new row'
cells(Target.Row + 1, 1).Select
End If
End Sub
Well... after a lot of experimenting gathering pieces of code from a lot of places and then debugging I ended up with the following VBA macro. Hope it helps! :)
When TAB or ENTER key is pressed the Sub Worksheet_Change will run.
It will check if it's column F being left...
If true => insert new row and select first cell [A]n where n = row number.
VBA macro code
Private Sub Worksheet_Change(ByVal Target As Range)
'Do nothing if more than one cell is changed or content deleted
If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
'Column F
If Target.Column = "6" Then
'Insert new row bellow
ActiveCell.EntireRow.Offset(1, 0).Insert
'Select first cell of next row just inserted
ActiveSheet.Cells(ActiveCell.Row + 1, 1).Select
End If
End Sub
Private Sub Workbook_Activate()
Application.OnKey "{TAB}", "Worksheet_Change" 'TAB key press
Application.OnKey "~", "Worksheet_Change" 'Keyboard ENTER press
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "{TAB}"
Application.OnKey "~"
End Sub
Maybe I'm missing something on the issue, but if you select your six columns and transform the selection with the "create list" command, then whenever you tab to the last cell of a line you'll automatically going to the next line. Furthermore, if you're at the last line, a new one will be created. IM not sure why you need a macro for that ?

Resources