Auto sort and format and Excel - vba

I have a table of clients in Excel, and I want to be able to add new client into the last row of the table and excel will sort the table automatically so that the client's name will be sorted in alphabetical order.
Also, that the format will be similar to the previous line. for example, the second column is DOB, so I want the format to be the same as the previous row MM/DD/YYYY
Thanks

Put the attached code in your worksheet module and it will sort your column A automatically.
Private Sub Worksheet_Change(ByVal Target As Range)
'turn off updates to speed up code execution
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
If Not Intersect(Target, Columns(1)) Is Nothing Then
With ActiveSheet.Sort
.SetRange Range("A1:X" & Cells(Rows.Count, 1).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("B").NumberFormat = "MM/DD/YYYY"
End If
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayAlerts = True
End With
End Sub

Here's a piece of VBA that would auto-add your table as soon as the first cell on the last row gets typed in. You would have to provide IsChangeInLastLineOfStrRange function and call AddEmptyRowWhenFull from the change-event. It might need tweaking since I removed some code from it. The original has a recursion timer to prevent ... well ... recursion.
Public Sub AddEmptyRowWhenFull(SheetName As String, Area As String, Target As Range)
Dim rngDatabase As Range
With Sheets(SheetName)
If IsChangeInLastLineOfStrRange(SheetName, Area, Target) _
And Target.Value <> "" Then
Set rngDatabase = .Range(Area)
AddEmptyRow rngDatabase, rngDatabase.Rows.Count
End If
End With
End Sub
Public Sub AddEmptyRow(Database As Range, RowPosition As Long, Optional ClearLine As Boolean = True)
Dim bScreenupdate, iCalculation As Integer
Dim colnum As Long, markrow As Long
Dim bUpdate As Boolean
bScreenupdate = Application.ScreenUpdating
iCalculation = Application.Calculation
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
With Database
If RowPosition < .Rows.Count Then
.Rows(RowPosition - 0).Copy 'Insert in and after data
.Rows(RowPosition + 1).Insert shift:=xlDown
Else
.Rows(RowPosition - 0).Copy 'Add line at end by inserting before last line
.Rows(RowPosition - 0).Insert shift:=xlDown ' to prevent cell formatting below it to be copied too
RowPosition = RowPosition + 1 'Clear last of the copies
End If
If ClearLine = False Then 'Move cursor down
ActiveSheet.Cells(ActiveCell.row + 1, ActiveCell.column).Activate
Else
For colnum = 1 To .Columns.Count 'Preserve formula's
If Not .Rows(RowPosition).Cells(1, colnum).HasFormula Then 'changed
.Rows(RowPosition).Cells(1, colnum).ClearContents
End If
Next colnum
End If
'Fix rowheight if we shift into other heights
.Rows(RowPosition + 1).RowHeight = .Rows(RowPosition + 0).RowHeight
End With
If bScreenupdate = True Then Application.ScreenUpdating = True
If Not iCalculation = xlCalculationManual Then Application.Calculation = iCalculation
End Sub
Arjen.

Related

.Select doesn't work when accessing a seperate excel file in vba. Why?

I am creating a code that opens another file, performs some action and closes it. In the file I am opening, there is a function that organizes the data upon closing.
I do not know how to code the filter in VBA, so I recorded a macro and pasted it into my function. The code works when I run it by itself, but when I call the main function the '.Select' doesn't appear to select the cells/columns, causing a failure.
The first function is from the first workbook, and the second is being called when the first function closes the file.
'*********First Function************
Sub AddDrawing_Button() 'activated by button in worksheet
PN = Sheets("New Drawing").Range("C5").Cells(1, 1).Value 'Part Number, D
Rev = Sheets("New Drawing").Range("C5").Cells(3, 1).Value 'Revision, E
Application.ScreenUpdating = False
Workbooks.Open ("C:\Users\Desktop\MasterDataFile.xlsm") 'Finds the file
Workbooks("MasterDataFile").Worksheets("DATA").Activate
t = Sheets("DATA").Range("D65536").End(xlUp).Row + 1 'finds the bottom row + 1
Sheets("DATA").Range("D1").Cells(t, 1).Value = PN 'Part Number, D
Sheets("DATA").Range("D1").Cells(t, 8).Value = Rev 'Revision, E
Workbooks("MasterDataFile").Close SaveChanges:=True
'upon closing this file, it jumps to the following code
Application.ScreenUpdating = True
End Sub
'*********Second Function in Second Workbook************
Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ThisWs As Worksheet
Dim value1 As String
Dim value2 As String
Set ThisWs = Workbooks("MasterDataFile").Worksheets("DATA")
t = ThisWs.Range("D65536").End(xlUp).Row 'end
'Application.ScreenUpdating = False
'The following 6 lines creates a new column and populates
' each row with the part number and revision combined.
Cells(1, 24) = "Order"
For s = 2 To t
value1 = Cells(s, 4)
value2 = Cells(s, 11)
ThisWs.Cells(s, 24) = value1 + "Rev" + value2
Next s
'The following was generated by recording a macro, and uses
' the filter to organize the data. The error is occurring
' because the columns are not being selected. Why?
ThisWs.Columns("D:X").Select
Selection.AutoFilter
ThisWs.AutoFilter.Sort.SortFields.Clear
ThisWs.AutoFilter.Sort.SortFields.Add Key:=Range( _
"X1:X19519"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ThisWs.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'This turns off the filter
ThisWs.Range("A1").Select
ThisWs.Columns("D:X").Select
Selection.AutoFilter
ThisWs.Range("A1").Select
'This deletes the generated column after it has been sorted
ThisWs.Columns("X:X").ClearContents
'Application.ScreenUpdating = True
End Sub
Can someone help me understand why the cells are not being selected, with a way to fix it?
Or if all else fails, can someone post a way to filter the columns without selecting anything.
Thank you.
I have rebuilt your function, It is untested and should work, but it is not completely optimised. Everything is handled in the original function and nothing is handled in the OnClose Event.
'*********First Function************
Sub AddDrawing_Button() 'activated by button in worksheet
Dim wbMasterDataFile as Workbook
Dim shtData as Worksheet
Dim t as long
Dim s as long
'PN = Sheets("New Drawing").Range("C5").Value 'Part Number, D
'Rev = Sheets("New Drawing").Range("C7").Value 'Revision, E
Application.ScreenUpdating = False
set wbMasterDataFile = Workbooks.Open ("C:\Users\Desktop\MasterDataFile.xlsm") 'Finds the file
set shtData = wbMasterDataFile.Worksheets("DATA")
with shtData
t = .Range("D65536").End(xlUp).Row + 1 'finds the bottom row + 1
.Range("D1").Cells(t, 1).Value = Sheets("New Drawing").Range("C5").Value 'Part Number, D
.Range("K1").Cells(t, 1).Value = Sheets("New Drawing").Range("C7").Value 'Revision, E
.Cells(1, 24).Value2 = "Order"
For s = 2 To t
.Cells(s, 24) = .Cells(s, 4) + "Rev" + .Cells(s, 11)
Next s
.Columns("D:X").AutoFilter
With .AutoFilter.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("X1:X19519"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
.Columns("D:X").AutoFilter
.Columns("X:X").ClearContents
End with
set shtData = nothing
wbMasterDataFile.Close SaveChanges:=True
set wbMasterDataFile = Nothing
'upon closing this file, it jumps to the following code
Application.ScreenUpdating = True
End Sub
I have also made some more direct references to the ranges that you are using not through the Cell function
I have to run so can't explain more but will edit with more detail later.
Thank you #Bullfrog for providing me the solution to my problem, I am only posting this because I do not want other vba users to get hung up on code that may not run.
Sub AddDrawing_Button()
Dim ThisWb As Workbook, wbMasterDataFile As Workbook
Dim ThisWs As Worksheet, shtData As Worksheet
Dim t As Long, s As Long
Dim value1 As String, value2 As String
Application.ScreenUpdating = False
Set ThisWb = Workbooks("CombinationIndex")
Set ThisWs = ThisWb.Worksheets("New Drawing")
Set wbMasterDataFile = Workbooks.Open("C:\Users\Desktop\MasterDataFile.xlsm")
Set shtData = Workbooks("MasterDataFile").Worksheets("FinalDATA")
With shtData
t = .Range("D65536").End(xlUp).Row + 1 'Finds the bottom row
.Range("D1").Cells(t, 1).Value = ThisWs.Range("C5").Value 'Part Number, D
.Range("D1").Cells(t, 8).Value = ThisWs.Range("C13").Value 'Revision , E
.Cells(1, 24).value2 = "Order" 'header to new column
For s = 2 To t
value1 = .Cells(s, 4) 'originally Bullfrog's code was giving me an error due to a type mismatch
value2 = .Cells(s, 11) 'I defined a variable above, and filled it so that it was always a string
.Cells(s, 24) = value1 + "0Rev" + value2 'will use the combined values to sort data by latest rev
Next s
.Columns("D:X").AutoFilter 'using the with function to apply the filter
With .AutoFilter.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("X1:X19519"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
.Columns("D:X").AutoFilter 'Turns off the filter
.Columns("X:X").ClearContents 'deletes the data
End With
Set shtData = Nothing
wbMasterDataFile.Close SaveChanges:=True 'closes the file
Set wbMasterDataFile = Nothing
Application.ScreenUpdating = True
End Sub

How to optimize this code, excel hangs for a second or two what to do?

Excel workbook hangs for a second or two when I run this code...
What to do?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim a As Variant
Dim b As Variant
Dim Number_of_Sims As Integer
Number_of_Sims = 76
For i = 3 To Number_of_Sims
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 'don't run unless change in column A
Application.EnableEvents = False 'stop executing this code until we are done
If Len(Range("s10").Value) = 0 Then
a = Cells(i, 23).Value
Cells(9, 19).Value = a
b = Cells(16, 19).Value
Cells(i, 24).Value = b
End If
Next
Application.EnableEvents = True
End Sub
First of all, you need to free the loop of the things that don't depend of the loop like :
Application.EnableEvents = False
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
And then your a and b seems to be useless, so I just gathered the 2 lines!
So give this a try, that should be more efficient :
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 'don't run unless change in column A
With Application
.EnableEvents = False 'stop executing this code until we are done
.DisplayAlerts = False
.ScreenUpdating = False
'.Calculation = xlCalculationManual
End With
Dim Number_of_Sims As Integer
Number_of_Sims = 76
If Len(Range("s10").Value) <> 0 Then
Else
For i = 3 To Number_of_Sims
Cells(9, 19).Value = Cells(i, 23).Value
Cells(i, 24).Value = Cells(16, 19).Value
Next i
End If
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub

Automatically sort multiple tables in a sheet upon change

I'm only about three weeks into learning how to use Excel, and I have it so that all of the tables on my worksheet will sort, but not when there's a change, only when I actually visit the worksheet.
So if I input data from another source like a UserForm, it won't sort the tables again until I go back to the worksheet. Is there a way to automatically sort them so the extra visit isn't needed?
This is what I have so far:
Private Sub Worksheet_Activate()
Dim tbl As ListObject
Dim SortCol As Long
Application.ScreenUpdating = False
For Each tbl In ActiveSheet.ListObjects
If tbl.Name = "TableSORT2" Then
SortCol = 2
Else
SortCol = 1
End If
With tbl.Sort
.SortFields.Clear
.SortFields.Add Key:=tbl.DataBodyRange.Columns(SortCol), _
SortOn:=xlSortOnValues, Order:=xlAscending
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next tbl
Application.ScreenUpdating = True
End Sub
I tried changing Private Sub Worksheet_Activate() to Private Sub Worksheet_Change() but to no avail, I'm assuming because there's more references or integration needed.
You can either take on D_Zab's advise or try below:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo halt
Application.EnableEvents = False
Dim tbl As ListObject
For Each tbl In Me.ListObjects
If Not Intersect(Target, Me.Range(tbl.Name)) Is Nothing Then
MsgBox "Table Updated"
SortTables Me 'call the sort table routine
End If
Next
moveon:
Application.EnableEvents = True
Exit Sub
halt:
MsgBox Err.Description
Resume moveon
End Sub
So above detects any changes made in any table in the sheet you put the event. Now, all you have to do is to create a sub that sorts all the tables and call it. A sample code (which is actually what you have) is below.
Private Sub SortTables(sh As Worksheet)
Dim tbl As ListObject
Dim SortCol As Long
Application.ScreenUpdating = False
For Each tbl In sh.ListObjects
If tbl.Name = "TableSORT2" Then
SortCol = 2
Else
SortCol = 1
End If
With tbl.Sort
.SortFields.Clear
.SortFields.Add Key:=tbl.DataBodyRange.Columns(SortCol), _
SortOn:=xlSortOnValues, Order:=xlAscending
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next tbl
Application.ScreenUpdating = True
End Sub
Is this what you're trying? Btw, for some reason, this also detects changes made from UserForms. Even a simple line like Range("A2").Value = "something" is detected so long as the target range is within the Table Range. Moreover, this also detects the addition of data to tables when it auto-resize. HTH.

VBA copy paste array/range onto another tab

Im trying to copy specific rows in a long list containing certain titles onto its own tab.
I had a system that worked using entirerow.copy Destination:= but this was quite untidy and took very long as I had a runclick to work with over 10 modules at once (which had to work with over 3500 rows.
So far I have this but I know the paste part is missing (I'm unsure what to put essentially). This basic format worked very well for me in another macro for formatting cells but obviously it is not quite the same.
Sub Anasuria()
Dim i As Long, LastRow As Long
Dim phrases
Dim rng1 As Range
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.Calculation = xlCalculationManual
End With
Sheets("Anasuria").Range("A40:AZ10000").ClearContents
phrases = Array("ANASURIA-Central", "ANASURIA-Env. Trading Sys.", "ANASURIA-Fulmar", _
"COOK-Anasuria allocation", "GUILLEMOT-Fulmar Gas")
With Sheets("Main")
LastRow = .Range("A" & Rows.Count).End(xlUp).Row
For i = 40 To LastRow
If Not IsError(Application.match(.Range("A" & i).Value, phrases, 0)) Then
If rng1 Is Nothing Then
Set rng1 = Sheets("Anasuria").Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
End If
rng1.PasteSpecial
Next i
End With
With Application
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.ScreenUpdating = True
End With
End Sub
Basically I want the relevant rows to be copied into the "Anasuria" sheet starting at row i.
I have modified your code a little and it should work (just edit range to your needs). One more thing: did you think of using advanced filter? I think it would give you the same results.
Sub Anasuria()
Dim i As Long, LastRow As Long, LastRowAna As Long
Dim phrases
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.Calculation = xlCalculationManual
End With
Sheets("Anasuria").Range("A1:AZ10").ClearContents
phrases = Array("ANASURIA-Central", "ANASURIA-Env. Trading Sys.", "ANASURIA-Fulmar", _
"COOK-Anasuria allocation", "GUILLEMOT-Fulmar Gas")
LastRow = Sheets("Main").Range("A" & Rows.Count).End(xlUp).Row
LastRowAna = Sheets("Anasuria").Range("A" & Rows.Count).End(xlUp)
For i = 1 To LastRow
If Not IsError(Application.Match(Sheets("Main").Range("A" & i).Value, phrases, 0)) Then
Sheets("Main").Range("A" & i).EntireRow.Copy Sheets("Anasuria").Range("A" & LastRowAna + 1) 'copy/paste part you needed ;)
LastRowAna = LastRowAna + 1
End If
Next i
With Application
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.ScreenUpdating = True
End With
End Sub

Excel VBA- Toggle row highlighting with each click of a macro

I have a macro that highlights a row if there is anything blank text in a specific column. This macro is used to highlight areas where a user needs to direct attention. I want to be able to unhighlight those rows after changes have been made, by clicking the same macro button.
How do I do this?
This is the current macro:
Sub Macro13()
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
With ActiveSheet
.Select
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
.DisplayPageBreaks = False
Firstrow = 2
LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
For Lrow = LastRow To Firstrow Step -1
With .Cells(Lrow, "M")
If .Value = "" Then
.EntireRow.Interior.ColorIndex = 3
End If
End With
Next Lrow
End With
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.Calculation = CalcMode
End With
End Sub
My idea was to, at the beginning of the macro, check to see if any row was highlighted red. If so, run a new loop that iterates through all columns, removing the cell highlighting, and then after that loop is done, break out of the macro. This is ugly and riddled with errors, though.
Sub Macro13() 'Checks for Incorrect Countries
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
With ActiveSheet
.Select
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
.DisplayPageBreaks = False
Firstrow = 2
LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
FirstrowA = 2
LastRowA = .Cells(.Rows.Count, "M").End(xlUp).Row
For Lrow = LastRow To Firstrow Step -1
With .Cells(Lrow, "M")
If .EntireRow.Interior.ColorIndex = 3 Then
For LrowA = LastRowA To FirstrowA Step -1
.EntireRow.Interior.ColorIndex = xlColorIndexNone
Next LrowA
End
Exit Sub
End If
If .Value = "" Then
.EntireRow.Interior.ColorIndex = 3
End If
End With
Next Lrow
End With
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.Calculation = CalcMode
End With
End Sub
This should do the trick for you. I've added a loop that looks for any formatting before it starts highlighting blanks. If if finds something red, it clears the whole sheet of red formatting and raises a flag (Tracker = True). When the flag is raised, the macro will not
format blank cells' rows as red. I tested it and it worked for me.
Sub Macro13()
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
With ActiveSheet
.Select
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
.DisplayPageBreaks = False
Firstrow = 2
LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
Dim Tracker As Boolean
Tracker = False
For Lrow = LastRow To Firstrow Step -1
If .Cells(Lrow, "M").EntireRow.Interior.ColorIndex = 3 Then
.Cells.Interior.ColorIndex = 0
Tracker = True
Exit For
End If
Next Lrow
If Tracker = False Then
For Lrow = LastRow To Firstrow Step -1
With .Cells(Lrow, "M")
If .Value = "" Then
.EntireRow.Interior.ColorIndex = 3
End If
End With
Next Lrow
End If
End With
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.Calculation = CalcMode
End With
End Sub
I've had a similar issue before and conditional formating didn't work well for me. I used something similar to this:
Sub CheckAndHighlight(area As Range, Optional ByVal searchValue As String = "")
Application.ScreenUpdating = False
Dim r As Range
For Each r In area
r.EntireRow.Interior.ColorIndex = 0
If r.Value = searchValue Then
r.EntireRow.Interior.ColorIndex = 3
End If
Next
Application.ScreenUpdating = True
End Sub