excel automatically Alphabetical - excel

people, my doubts is simple .. I created a spreadsheet in excel with several fields, eg:
NAME ADDRESS PHONE
carlos ave. 1 12345678
Argeu av .2 87654321
After this, I used the following code in the module:
Private Sub Worksheet_Activate()
ActiveSheet.ScrollArea = "$A$2:$A$300"
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Column <> 1 Then Exit Sub
Dim LR As Long
LR = Cells(Rows.Count, "A").End(xlUp).Row
Range("$A$2:$A" & LR).Sort Key1:=Range("$A$2")
End Sub
This code will make in the example table, the Argeu stand on the carlos, so far so good, but I want when the Argeu is up from carlos the phone and address data also rise ..
If anyone can help, thank you

IF you want Col C to be also sorted then include that in the sort range as well. See this.
Change
Range("$A$2:$A" & LR).Sort Key1:=Range("$A$2")
to
Range("$A$2:$C" & LR).Sort Key1:=Range("$A$2")
EDIT
Your code can be properly re-written as
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
'~~> For xl2007+ use .CountLarge
If Target.Cells.CountLarge > 1 Then Exit Sub
'~~> For xl2003 use .Count
'If Target.Cells.Count > 1 Then Exit Sub
Dim LR As Long
If Application.WorksheetFunction.CountA(Cells) <> 0 Then
LR = Cells.Find(What:="*", _
After:=Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
LR = 1
End If
Range("$A$2:$C" & LR).Sort Key1:=Range("$A$2")
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
ScreenShot

Related

Auto change number in a column when duplicate number entered

I am try to get a column number to change automatically, by -1, if the same number is entered in the same column again.
Basically I am sorting a list 1 to whatever and then auto sort and change everything below that new number to change by -1. I have the VBA to auto sort as I go but the change in number has me stumped.
Starting point:
If I change D9 to 5 I need it to move into that position (D6) and change D7:D11 by -1
I already have the VBA for the sorting:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("A:d")) Is Nothing Then
Range("D1").Sort Key1:=Range("D2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
but really need help with the other.
What you are asking for will work if a cell in column D is changed to a value greater than its current value. It won't work if its changed to a value less than its current value.
Here's a solution that works for both
Note: this assumes column D starts out numbered sequentialy from 1 and sorted. If not, you'll get weird results.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim TargetRow As Long, i As Long, lr As Long
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Range("d:d")) Is Nothing Then
On Error GoTo EH
TargetRow = Target.Row
Application.EnableEvents = False
lr = Me.Cells(Me.Rows.Count, 4).End(xlUp).Row
If Target.Value2 >= TargetRow Then
If Target.Value2 >= lr Then Target.Value2 = lr - 1
For i = TargetRow + 1 To Target.Value2 + 1
Me.Cells(i, 4).Value2 = Me.Cells(i, 4).Value2 - 1
Next
ElseIf Target.Value2 < TargetRow - 1 Then
If Target.Value2 <= 0 Then Target.Value2 = 1
For i = Target.Value2 + 1 To TargetRow - 1
Me.Cells(i, 4).Value2 = Me.Cells(i, 4).Value2 + 1
Next
End If
Me.Range("A1:D" & lr).Sort Key1:=Me.Range("D2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom
End If
EH:
Application.EnableEvents = True
End Sub

How can I change this VBA to not return an error when deleting a row?

I was trying to find a VBA code that would move rows from one sheet to another and found this block of code. It works perfectly, except for when I delete an entire row. When I delete an entire row it gives me this error.
Here's the VBA code i'm using. How can I change it so it doesn't give me this error?
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Intersect(Target, Range("A:A,Y:Y")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Dim bottomB As Long
Select Case Target.Column
Case Is = 1
bottomB = Sheets(Target.Value).Range("A:A").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Range("A" & Target.Row).Resize(, 25).Copy Sheets(Target.Value).Cells(bottomB, 1)
Target.EntireRow.Delete
End Select
Application.EnableEvents = True
End Sub
It will throw this error if multiple cells get changed at the same time so when the change event code triggers you may check to see if multiple cells are changed and then exit the code.
Try this code to see if this resolves the issue you are having.
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Intersect(Target, Range("A:A,Y:Y")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Dim bottomB As Long
Select Case Target.Column
Case Is = 1
bottomB = Sheets(Target.Value).Range("A:A").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Range("A" & Target.Row).Resize(, 25).Copy Sheets(Target.Value).Cells(bottomB, 1)
Target.EntireRow.Delete
End Select
Application.EnableEvents = True
End Sub

creating a complex macro using vba

I have a complex workbook that i need filtered using vba.
I need to delete rows that have blank cells from column G.
I then need columns C through G hidden.
Then I need Column H filtered to delete all rows greater than 2.
Finally I need Column I sorted from Largest to smallest.
This is what i have so far but It half way works and i don't want to use a command button. I want to be able to paste a document in here and the code automatically works it.
Private Sub CommandButton1_Click()
'Created by William Hinebrick 277096
Dim xRg As Range
Dim xTxt As String
On Error Resume Next
If ActiveWindow.RangeSelection.Count > 1 Then
xTxt = ActiveWindow.RangeSelection.AddressLocal
Else
xTxt = ActiveSheet.UsedRange.AddressLocal
End If
Set xRg = Application.InputBox("Please select range:", "Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
If (xRg.Areas.Count > 1) Or (xRg.Columns.Count > 1) Then
MsgBox "You can only select one column per time", vbInformation, "Kutools for Excel"
Exit Sub
End If
xRg.Range("A1").EntireRow.Insert
Set xRg = xRg.Range("A1").Offset(-1).Resize(xRg.Rows.Count + 1)
xRg.Range("A1") = "Temp"
xRg.AutoFilter 1, ">2"
Set xRg = Application.Intersect(xRg, xRg.SpecialCells(xlCellTypeVisible))
On Error GoTo 0
If Not xRg Is Nothing Then xRg.EntireRow.Delete
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
'Created by William Hinebrick 277096
Dim xRg As Range
Application.ScreenUpdating = False
For Each xRg In Range("G1:G10000")
If xRg.Value = "" Then
xRg.EntireRow.Hidden = True
Else
xRg.EntireRow.Hidden = False
End If
Next xRg
Application.ScreenUpdating = True
End Sub
Sub Column_Hide()
'Created by William Hinebrick 277096
Columns("C:G").EntireColumn.Hidden = True
Columns("J").EntireColumn.Hidden = True
End Sub
Private Sub Sort_Drop(ByVal Target As Range)
On Error Resume Next
Range("I1").Sort Key1:=Range("I2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End Sub
I would like to be able to use this daily as I will be pasting New spreadsheets to this worksheet to be filtered so I may concise the results
This should do everything listed.
If you require it to perform everytime you copy data in, then the Worksheet_Changeevent from your 2nd sub is the way to go. But this means it also runs every other time you change something in your workbook. I'd personally simply assign a Keyboard shortcut to it. Seems the easiest way to go.
Option Explicit
Sub test()
Dim i As Double
Dim lastrow As Double
lastrow = ActiveSheet.UsedRange.Rows.Count
For i = lastrow To 2 Step (-1) 'delete empty G cells
If ActiveSheet.Cells(i, 7).Value = "" Then Cells(i, 7).EntireRow.Delete
Next
lastrow = ActiveSheet.Cells(Rows.Count, 7).End(xlUp).Row
For i = lastrow To 2 Step (-1) 'delete H >2
If ActiveSheet.Cells(i, 8).Value > 2 Then Cells(i, 8).EntireRow.Delete
Next
Columns("C:G").EntireColumn.Hidden = True 'hide columns
Range("I1").Sort Key1:=Range("I2"), _
Order1:=xlDescending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom 'Sort by I descending order
End Sub

Create button to copy row from Sheet 1 to Sheet 2

I have Worksheet 1, with columns A to D.
I would like to create a button executing row to be copied to Worksheet 2, as soon as cell C in Worksheet 1 is populated.
I have no experience in Excel at all, so far I found and altered this macro code for my needs:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 3 And Target.Cells.Count = 1 Then
Target.EntireRow.Copy _
Destination:=Sheets(2).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End If
End Sub
But when I try to create a button to execute this macro, it would never work. Could anyone help me solve this, please.
Is this what you are trying? Read more about Worksheet_Change HERE
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim lRow As Long
On Error GoTo Whoa
Application.EnableEvents = False
If Target.Cells.CountLarge > 1 Then Exit Sub
Set ws = ThisWorkbook.Sheets("Sheet2")
lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row + 1
If Not Intersect(Target, Columns(3)) Is Nothing Then _
Target.EntireRow.Copy Destination:=ws.Rows(lRow)
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
EDIT:
If the code still doesn't work then from the VBA Editor, press CTRL + G to bring up the immediate window and type this
Application.EnableEvents = True
and press ENTER key and now the code should work.

SpecialCells causing SheetSelectionChange event in Excel 2010

I have a test Macro
Sub test()
Dim rSrcMatrix As Range
Set rSrcMatrix = Sheets("Code Matrix").Range("Xfer_To_Xfer_Matrix").Range("A1")
Set rSrcMatrix = rSrcMatrix.Resize(rSrcMatrix.SpecialCells(xlCellTypeLastCell).Row, rSrcMatrix.SpecialCells(xlCellTypeLastCell).Column)
End Sub
I am using this macro to test my COM addin that I have created in VS2010. I have delegated the SheetSelectionChange event in the addin to some function.
Now I notice that whenever I run this macro, Excel fires the SheetSelectionChange event 4 times and my addin calls the associated method for that many times.
Is there anything that I am missing or is this a bug in excel?
I believe and I could be wrong because I couldn't find an MSDN article to prove it but SpecialCells performs a type of selection and triggers the Worksheet_SelectionChange or the Workbook_SheetSelectionChange event and hence you need to switch off events.
Here is a simple way to test it.
Place this code in the Sheet Code Area
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
MsgBox "Damn! The SpecialCells caused me to pop up!!!"
End Sub
Sub test()
Debug.Print ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
End Sub
Worksheet_SelectionChange and Workbook_SheetSelectionChange do the same job. Worksheet_SelectionChange is used in the sheet code are for a specific sheet. And Workbook_SheetSelectionChange is used when you want the event to fire across all the sheets in that workbook.
YOUR QUESTION FROM THE COMMENT: What if we wanted to associate another event with that line of code. In that case, we cannot suppress the event.
Now, we have two alternatives. Based on your above question we cannot use Alternative One. So you may directly skip to Alternative 2
ALTERNATIVE 1
Switch Off Events
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
'
'~~> YOUR CODE
'
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
ALTERNATIVE 2
Instead of using SpecialCells to find the last row or the last column, we will use .Find.
Sub test()
Dim ws As Worksheet
Dim rSrcMatrix As Range
Dim Lrow As Long, LCol As Long
Set ws = ThisWorkbook.Sheets("Code Matrix")
With ws
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
Lrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
LCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
Lrow = 1
End If
Set rSrcMatrix = .Range("Xfer_To_Xfer_Matrix").Range("A1")
Set rSrcMatrix = rSrcMatrix.Resize(Lrow, LCol)
Debug.Print rSrcMatrix.Address
End With
End Sub
Based on #Siddharth Rout technique, here is a method that will return the last cell of a Worksheet.UsedRange (see my comments below his answer)
Function GetLastCellEmpty(rng As Range) As Range
Set m_rngCheck = rng
Set m_rngFound = m_rngCheck.Find(What:="", _
LookIn:=XlFindLookIn.xlFormulas, _
Lookat:=XlLookAt.xlPart, _
SearchDirection:=XlSearchDirection.xlPrevious)
Set GetLastCellEmpty = m_rngFound
End Function
Function GetLastCellUsedRange(ws As Worksheet) As Range
Set GetLastCellUsedRange = GetLastCellEmpty(ws.UsedRange.Offset(1, 1)).Offset(-1, -1)
End Function

Resources