Sorting not working - excel

In this user form
I have the following code (Ascending is by default TRUE, while Descending is False)
Private Sub OKButton_Click()
Dim rRange As Range
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row
On Error Resume Next
Application.DisplayAlerts = False
Set rRange = Application.InputBox(Prompt:="Please select a cell in the column you want
_to sort", Title:="SPECIFY COLUMN", Type:=8)
Col = rRange.Columns(1).Column
On Error GoTo 0
Application.DisplayAlerts = True
If rRange Is Nothing Then
Exit Sub
Else
If AscendingOption Then
Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow), Order2:=xlAscending, Header:=xlNo
End If
If DescendingOption Then
Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlDescending, key2:=Range("C14:C" & lastRow), Order2:=xlAscending
End If
End If
End Sub
When I click OK nothing happens: not an error message, nor any action.
Can anybody help me finding the error?

Both variables AscendingOption and DescendingOption are not initialized so are set as false. You need to change value of one of them into TRUE to sort. But in current code if both are TRUE, you will sort it twice - firstly ascending and secondly descending. You can reduce code by one variable into:
If AscendingOption Then
Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow), Order2:=xlAscending, Header:=xlNo
Else
Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14", Col & lastRow), Order1:=xlDescending, key2:=Range("C14:C" & lastRow), Order2:=xlAscending
End If
If AscendingOption is true, it sorts in in ascending order, otherwise descending.

This is the version of the code which works fine:
Private Sub OKButton_Click()
Dim rRange As Range
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row
Application.DisplayAlerts = False
Set rRange = Application.InputBox(Prompt:="Please select a cell in the column
_you want to sort", Title:="SPECIFY COLUMN", Type:=8)
Col = rRange.Columns(1).Column
On Error GoTo 0
Application.DisplayAlerts = True
If rRange Is Nothing Then
Exit Sub
Else
If AscendingOption Then
Range("A14:CE" & lastRow).Sort key1:=Range(Cells(14, Col), Cells(lastRow, Col)),
_Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow),
_Order2:=xlAscending, Header:=xlNo
End If
If DescendingOption Then
Range("A14:CE" & lastRow).Sort key1:=Range(Cells(14, Col), Cells(lastRow, Col)),
_Order1:=xlDescending, Header:=xlNo, key2:=Range("C14:C" & lastRow),
_Order2:=xlAscending, Header:=xlNo
End If
Unload UserForm1
End If
End Sub

Related

Copy paste stopped working after upgrade to 365

Hi I have bit of a code that has worked for a long time but it no longer works, we have recently been upgraded to 365, The code filers data on one worksheet then copies and paste into another worksheet but the paste no longer works. I am new to this so any help is much appreciated.
Thanks in advance.
This is the bit of code which is part of a longer module
Application.StatusBar = "GENERATE LIST OF LICENSES DUE TO EXPIRE"
Sheets("due to expire").Select
Columns("A:I").Select
Selection.ClearContents
Sheets("Import").Select
Range("B1").Select
Selection.AutoFilter
Dim lngStart As Long, lngEnd As Long
lngStart = Range("M1").Value 'assume this is the start date
lngEnd = Range("P1").Value 'assume this is the end date
Range("a1:I5000").AutoFilter field:=9, _
Criteria1:=">=" & lngStart, _
Operator:=xlAnd, _
Criteria2:="<=" & lngEnd
Range("a1:i5000").Select
Selection.Copy
Sheets("due to expire").Select
Range("a1").Select
ActiveSheet.PasteSpecial
Cells.EntireColumn.AutoFit
Number_of_Records = Sheets("Main").Range("L7").Value + 2
Selection_Range = Number_of_Records & ":1000000"
Rows(Selection_Range).Select
Selection.Delete Shift:=xlUp
Number_of_Records = Sheets("Main").Range("L7").Value + 1
Selection_Range = "J2:J" & Number_of_Records
Range("J2").Select
Selection.AutoFill Destination:=Range(Selection_Range)
Sheets("Import").Select
Range("B1").Select
Selection.AutoFilter
Range("C1").Select
Selection.AutoFilter
It could be the date format has changed so add a message box to check.
Sub DueToExpire()
Application.StatusBar = "GENERATE LIST OF LICENSES DUE TO EXPIRE"
Dim wsImport As Worksheet, wsDue As Worksheet
Dim lngStart As Long, lngEnd As Long
Set wsDue = Sheets("due to expire")
With wsDue
.Columns("A:I").ClearContents
End With
Set wsImport = Sheets("Import")
With wsImport
lngStart = .Range("M1").Value 'assume this is the start date
lngEnd = .Range("P1").Value 'assume this is the end date
MsgBox "Start date is " & Format(lngStart, "d mmm yyyy") & vbLf & _
"End date is " & Format(lngEnd, "d mmm yyyy")
With .Range("A1:I5000")
.AutoFilter Field:=9, Criteria1:=">=" & lngStart, _
Operator:=xlAnd, Criteria2:="<=" & lngEnd
.Copy
wsDue.Range("A1").PasteSpecial
.AutoFilter Field:=9
End With
End With
Number_of_Records = Sheets("Main").Range("L7").Value + 2
MsgBox "Number of records = " & Number_of_Records
With wsDue
.Rows(Number_of_Records & ":1000000").Delete Shift:=xlUp
.Range("J2").AutoFill Destination:=.Range("J2:J" & Number_of_Records - 1)
.Columns.AutoFit
End With
Application.StatusBar = ""
End Sub

subtotal wih conditonally group using VBA

I want to group column name :Check,Code No1,Code 2,Status and total result in Number column according to group using VBA
Data
Result
This is my code:
Sub Sample()
Dim ws As Worksheet, ws1 As Worksheet
Dim LastRowWs As Long, LastRowWs1 As Long, i As Long
Dim Delrange As Range
Application.ScreenUpdating = False
On Error GoTo Whoa
Set ws = Sheets("Sheet1"): Set ws1 = Sheets("Sheet2")
ws1.Cells.Delete
LastRowWs = ws.Range("A" & Rows.Count).End(xlUp).Row
LastRowWs1 = LastRowWs
ws.Range("A1:F" & LastRowWs).Copy ws1.Range("A1")
With ws1
.Columns("A:F").Sort Key1:=.Range("A:F"), Order1:=xlAscending, Key2:=.Range("B2") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=4, MatchCase:= _
True, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2 _
:=xlSortNormal
With .Range("A1:F" & LastRowWs1)
.Subtotal GroupBy:=2, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
.Subtotal GroupBy:=3, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
.Subtotal GroupBy:=4, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
End With
LastRowWs1 = .Range("D" & Rows.Count).End(xlUp).Row
'.Rows(LastRowWs1 + 1 & ":" & Rows.Count).ClearContents
.Range("A1:F" & LastRowWs1).Copy
.Range("A1:F" & LastRowWs1).PasteSpecial xlPasteValues
i = LastRowWs1
Do While i > 1
'If InStr(1, .Range("A" & i).Value, "", vbTextCompare) Then
If InStr(1, .Range("D" & i).Value, "Total", vbTextCompare) Then
i = i - 1
Else
If Delrange Is Nothing Then
Set Delrange = .Rows(i - 1)
Else
Set Delrange = Union(Delrange, .Rows(i))
'i = i - 1
End If
End If
i = i - 1
' End If
Loop
If Not Delrange Is Nothing Then Delrange.Delete: Set Delrange = Nothing
LastRowWs1 = .Range("D" & Rows.Count).End(xlDown).Row
'For i = LastRowWs1 To 2 Step -1
For i = 1 To LastRowWs1
If (InStr(1, .Range("D" & i).Value, "Total", vbTextCompare)) Then
.Range("F" & i - 1).Value = .Range("F" & i).Value
If Delrange Is Nothing Then
Set Delrange = .Rows(i)
Else
Set Delrange = Union(Delrange, .Rows(i))
End If
End If
Next i
If Not Delrange Is Nothing Then Delrange.Delete
.Cells.RemoveSubtotal
End With
MsgBox "Vandana, Please check Sheet 'Output' :-)"
LetsContinue:
Application.ScreenUpdating = True
On Error Resume Next
Set ws = Nothing: Set ws1 = Nothing
On Error GoTo 0
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
But result is like this
●★ 100 101 PG is same column group but sum result is separately
See like this:
Somethings you will need to change in Pivot Visualization:
Tabular Form Data
SubTotals Off
Totals Off
Item repeat for each column
Link to File

if match found delete from Multiple sheets

Sheet 0 : https://paste.pics/82a491cbc642d6fff555ef70612aec5b
Sheet 1 : https://paste.pics/cafe8628b76e56789cf03b06a923bde8
Sheet 2 : https://paste.pics/2320369d395a22c868b5e439b456ad3a
Sheet 3 : https://paste.pics/9fc84c7f43e1a2819d1537593c44c1f9
If match is found => "SUP" "AL" "AP" then Data should be cleared from all the sheets with one Button click
Button is in "Sheet0" => when clearing data the Headers should not get Cleared
if want to see my excel safe download 100%
https://drive.google.com/file/d/1w0n_srbhF02OhiWzKsB4IWWiwV5nO-Vl/view?usp=sharing
=========================================================================
This is my code where i tried But not working giving error at Ws.Range
Private Sub CommandCreate_new_Click()
Dim Ws As Worksheet
For Each Ws In Sheets(Array("Sheet1","Sheet2","Sheet3"))
Ws.Range ("I9:AM9")
.Cells.Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=True
.Cells.Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=False
.Cells.Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=True
.Cells.Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=False
Next Ws End Sub
========================================================================
Partially Working But not setting the Cell to => No fill Color [As match condition is found data should be deleted and even the cell color should be deleted and set to no fill color]
Private Sub CommandButton1_Click()
Dim Ws As Worksheet
For Each Ws In Sheets(Array("Sheet1", "Sheet2", "Sheet3"))
Ws.Range("A4", Ws.Range("A" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("B4", Ws.Range("B" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("C4", Ws.Range("C" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("D4", Ws.Range("D" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("E4", Ws.Range("E" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("F4", Ws.Range("F" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("G4", Ws.Range("G" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("H4", Ws.Range("H" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("I4", Ws.Range("I" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Ws.Range("J4", Ws.Range("J" & Rows.Count).End(xlUp).Offset(, 1)).ClearContents
Next Ws
End Sub
This is the below output i am getting after running the above partially code
[My output][1]: https://i.stack.imgur.com/6EbRP.png

sort ascending/descending vba excel

I want to sort a column (it's a flagcolumn with Y/N). It should Toggle between ascending / descending on every click.
my code is not working..I am new to VBA. Any help please.
Private Sub CommandButton1_Click()
Dim xlSort As XlSortOrder
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row End With
If (Range("E2").Value > Range("E" & CStr(LastRow))) Then
xlSort = xlAscending
Else
xlSort = xlDescending
End If
.Sort Key1:=Range("E2"), Order1:=xlSort, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
ActiveWorkbook.Save
End Sub
This code worked for me:
Private Sub CommandButton1_Click()
Dim xlSort As XlSortOrder
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
If (.Range("E2").Value > .Range("E" & CStr(LastRow))) Then
xlSort = xlAscending
Else
xlSort = xlDescending
End If
.Range("E2:E" & LastRow).Sort Key1:=.Range("E2"), Order1:=xlSort, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End With
ActiveWorkbook.Save
End Sub
Hope this does the trick!!!
This will be easier if you declare a range variable ("rng" in the example below). This code should fix it.
Private Sub CommandButton1_Click()
Dim xlSort As XlSortOrder
Dim LastRow As Long
Dim rng As Range
With ActiveSheet
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
Set rng = Range("E2").Resize(LastRow, 1)
With rng
If (.Cells(1).Value > .Cells(LastRow - 1).Value) Then
xlSort = xlAscending
Else
xlSort = xlDescending
End If
.Sort Key1:=.Cells(1), Order1:=xlSort, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End With
End With
ActiveWorkbook.Save
End Sub
To sort ascending and descending with 2 keys
Sub Button1_Click()
Dim xlSort As XlSortOrder
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
If (.Range("E2").Value > .Range("E" & CStr(LastRow))) Then
xlSort = xlAscending
Else
xlSort = xlDescending
End If
.Range("E2:E" & LastRow).Sort Key1:=.Range("E2"), Order1:=xlSort, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End With
ActiveWorkbook.Save
End Sub

Organizing by color

I have run into an issue, I have a script thanks to several members here has allowed me to import directly from a file into a workbook. With that same script I've incorporated the ability to organize by color red on top, and green underneith. I thought I could write the code to make it so that yellow would be in the middle myself, but it doesn't take into concideration it seems the difference between yellow and red, although I thought I did make that difference noticable though the script.
If someone can look at this and tell me where I am going wrong it would be greatly apprecaited.
This is what I get now for an end result, the yellow is on the bottom of the sheet btw after importing.
The code for some reason isn't reading right, so attached is also a link to the sheet, with the added file to import.
Zip File
or the files seperate here...
Sheet
CSV
Here is my code:
Option Explicit
Sub Update_POT()
Dim wsPOD As Worksheet
Dim wsPOT As Worksheet
Dim wsPOA As Worksheet
Dim cel As Range
Dim lastrow As Long, fstcell As Long, i As Long, Er As Long, lstCol As Long, lstRow As Long, strFile As String
Set wsPOD = Sheets("PO Data")
Set wsPOT = Sheets("PO Tracking")
Set wsPOA = Sheets("PO Archive")
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
With wsPOD
.Columns("A:AB").ClearContents
.Range("Y1").Formula = "=COUNTIFS('PO Tracking'!$D:$D,$C1,'PO Tracking'!$C:$C,$D1,'PO Tracking'!$F:$F,$G1)"
.Range("Z1").Formula = "=IF($M1,"""",""Different"")"
.Range("AA1").Formula = "=IF(ISBLANK($C1),0,1)"
.Range("AB1").Formula = "=IF($O1,""Full"","""")"
End With
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
With wsPOD.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=wsPOD.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
With wsPOD
'first bring columns F:G up to match their line
For Each cel In Intersect(.UsedRange, .UsedRange.Offset(5), .Columns(6))
If cel = vbNullString And cel.Offset(, -2) <> vbNullString Then
.Range(cel.Offset(1), cel.Offset(1, 1)).Copy cel
cel.Offset(1).EntireRow.Delete
End If
Next
'now fil columns A:D to match PO Date and PO#
For Each cel In Intersect(.UsedRange, .UsedRange.Offset(5), .Columns(1))
If cel = vbNullString And cel.Offset(, 5) <> vbNullString Then
.Range(cel.Offset(-1), cel.Offset(-1, 3)).Copy cel
End If
Next
lastrow = wsPOD.Cells(Rows.Count, "J").End(xlUp).Row
fstcell = wsPOD.Cells(Rows.Count, "N").End(xlUp).Row
wsPOD.Range("Y1:AB1").Copy wsPOD.Range("M" & fstcell & ":P" & lastrow)
wsPOD.Range("M:P").Calculate
End With
With Intersect(wsPOD.UsedRange, wsPOD.Columns("P"))
.AutoFilter 1, "<>Full"
With Intersect(.Offset(2).EntireRow, .Parent.Range("A:P"))
.EntireRow.Delete
End With
.AutoFilter
End With
With Intersect(wsPOD.UsedRange, wsPOD.Columns("N"))
.AutoFilter 1, "<>Different"
With Intersect(.Offset(2).EntireRow, .Parent.Range("A:P"))
.EntireRow.Delete
End With
.AutoFilter
End With
'Final Adjustments before transfering over to PO Tracking.
With wsPOD
.AutoFilterMode = False
lastrow = wsPOD.Cells(Rows.Count, "A").End(xlUp).Row
Intersect(.UsedRange, .Range("A4:A" & lastrow)).Cut .Range("Q3")
Intersect(.UsedRange, .Columns("D")).Cut .Range("R1")
Intersect(.UsedRange, .Columns("C")).Cut .Range("S1")
Intersect(.UsedRange, .Columns("B")).Cut .Range("T1")
Intersect(.UsedRange, .Columns("G")).Cut .Range("U1")
Intersect(.UsedRange, .Columns("F")).Cut .Range("V1")
End With
With wsPOD
wsPOD.Columns("A:P").ClearContents
lastrow = wsPOD.Cells(Rows.Count, "Q").End(xlUp).Row
wsPOD.Range("Q3:V" & lastrow).Copy wsPOT.Cells(Rows.Count, "B").End(xlUp).Offset(1)
End With
'Format PO Tracking
With wsPOT
.Range("Q1:U1").Copy
lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
.Range("V1:X1").Copy .Range("H3:J" & lastrow)
.Range("N2:O2").Copy .Range("N3:O" & lastrow)
.Range("P1:V1").Copy
.Range("B3:H" & lastrow).PasteSpecial xlPasteFormats
.Range("K3:K" & lastrow).Borders.Weight = xlThin
lastrow = .Cells(.Rows.Count, "H").End(xlUp).Row
.Range("H:J").Calculate
.Sort.SortFields.Clear
'Sort PO Tracking
'Sort Reds
.Sort.SortFields.Add(.Range("J3:J" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(1)
.Sort.SortFields.Add Key:=Range( _
"J3:J30" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
'Sort Yellows
.Sort.SortFields.Add(.Range("I3:I" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(2)
.Sort.SortFields.Add Key:=Range( _
"I3:I" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
'Sort Greens
.Sort.SortFields.Add(.Range("I3:I" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(3)
.Sort.SortFields.Add Key:=Range( _
"I3:I" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
With .Sort
.SetRange wsPOT.Range("B2:K" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
With wsPOD
wsPOD.Columns("Q:X").ClearContents
wsPOD.Cells(1, 25).Value = "=COUNTIFS('PO Tracking'!$D:$D,$C1,'PO Tracking'!$C:$C,$D1,'PO Tracking'!$F:$F,$G1)"
wsPOD.Cells(1, 27).Value = "=IF(ISBLANK($C1),0,1)"
wsPOD.Range("Y1:AB1").Copy wsPOD.Range("M5:P5")
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlCalculationAutomatic
End With
End Sub
You have to remove the line
.Sort.SortFields.Add Key:=Range( _
"I3:I" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
in
'Sort Yellows
.Sort.SortFields.Add(.Range("I3:I" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(2)
.Sort.SortFields.Add Key:=Range( _
"I3:I" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
You cannot have have the same duplicate sort conditions for both Yellow and Green in the same column. Remove that line and try again.

Resources