Sort ranges from 2 columns repeatedly in vba - excel

With below code I could sort data (marked with blue background) from 2 columns based on "B" column. Similarly I want to repeat the same for each blue block. I've highlighted cells manually just for illustration. Any help will be appreciated.
Code:
Sub SortRanges()
Dim firstcell As String
With Columns("B")
.Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate
firstcell = ActiveCell.Row
End With
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Add Key:=Range("B" & firstcell & ":B" & firstcell + 5), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet4").Sort
.SetRange Range("A" & firstcell & ":B" & firstcell + 5)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

Try a loop down your column and, as it looks like everything is blocks of 5, do something like:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if cells(i,1).interior.color = Blue Then `FIX THIS TO MATCH THE BLUE YOU WANT
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i
I may have not understood the part about your highlighting... if that blue is the "highlight" then you can modify the above such that:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if not isempty(cells(i,2)) Then
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i
One more thing... if you can just run 2 sorts in sequence, second should be your final sort, like:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if not isempty(cells(i,2)) Then
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,1),Cells(i+5,1)), order1:=xlAscending, Header:=xlNo
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i

Related

Excel VBA Reformat Data

I have some data that will always be 8 columns (A-H) the number of rows could be different every time (Dynamic).
If the string in column A ends with:
"IT", "LN" or "SJ" then the row value in Column G needs to be divided by 100.
If the string ends in "KK" the value in Column G needs to be
divided by 1000.
Otherwise no math operation to the row needs to be performed.
The data also needs to be sorted alphabetically by column C then by column H.
After this is done the header row (1). Can be deleted.
What I have so far "works" but it results in a very long list of 0.0000 values in column G that makes copying out the cleaned data difficult.
Would anyone be able to show me a more efficient solution?
Sub Clean()
Dim wkb As Workbook
Set wkb = ActiveWorkbook
Dim ws As Worksheet
Set ws = ActiveSheet
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add2 Key:=Range("H2:H2500" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ws.Sort
.SetRange Range("A1:H2500")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("I2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RIGHT(RC[-8],2) = ""SJ"", RIGHT(RC[-8],2) = ""LN"", RIGHT(RC[-8],2) = ""IT"", RIGHT(RC[-8],2) = ""KK""),IF(RIGHT(RC[-8],2) = ""KK"",RC[-2]/1000,RC[-2]/100),RC[-2])"
Range("I2").Select
Selection.Copy
Selection.End(xlToLeft).Select
Selection.End(xlDown).Select
Range("I2500").Select
Range(Selection, Selection.End(xlUp)).Select
Range("I3:I2500").Select
Range("I2500").Activate
ActiveSheet.Paste
Selection.End(xlUp).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Range("G2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.NumberFormat = "0.0000"
Columns("I").Delete
Dim strDataRange As Range
Dim keyRange As Range
Set strDataRange = Range("A:H")
Set keyRange = Range("C1")
strDataRange.Sort Key1:=keyRange, Header:=xlYes
Rows(1).Delete
End sub
Sample Input Data
Codes
Population
Animal
Type
Size
Housing Qty
Average Cost
Country
SHIB IT
4,504
DOGE
Standard
SMALL
15,019
9.5557
JP
CORG LN
33,052
DOGE
Standard
SMALL
8,816
31,404.9100
FR
SOG SJ
1,417
CAT
Standard
BIG
90
247.2508
ZM
CHOW KK
873
DOGE
Standard
BIG
9,192
177.2797
CN
FLOP AG
991
CAT
Standard
BIG
7
597.0650
BZ
Desired Output Data:
Please, try the next compact and fast code. It will place the range to be processed in an array and drop down the processed result at the end. Now it returns overwriting the existing range. It can be easily adapted to return in another sheet:
Sub processRangeAH()
Dim sh As Worksheet, lastR As Long, rng As Range, arr, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
Set rng = sh.Range("A1:H" & lastR)
rng.Sort Key1:=sh.Range("H1"), Order1:=xlAscending, Header:=xlYes
arr = rng.Value2
For i = 2 To UBound(arr)
Select Case UCase(Right(arr(i, 1), 2))
Case "IT", "LN", "SJ": arr(i, 7) = arr(i, 7) / 100
Case "KK": arr(i, 7) = arr(i, 7) / 1000
End Select
Next i
rng.Value2 = arr
rng.Sort Key1:=sh.Range("C1"), Order1:=xlAscending, Header:=xlYes
sh.Range("G2:G" & lastR).NumberFormat = "0.0000"
sh.rows(1).Delete
End Sub
I posted this answer some hours before, when I left my office, but by mistake, in another thread...
Just to see how an array can be used, in order to increase the speed for larger range.
Try this. It copies everything to a new sheet so you don't lose the original data. Could be sped up if you have lots of data.
Sub x()
Dim ws As Worksheet, r As Long
Set ws = Worksheets.Add
Sheet1.Range("A1").CurrentRegion.Copy ws.Range("A1") 'assumes data on sheet1 (code name, change to suit)
For r = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row
Select Case Right(ws.Cells(r, 1), 2)
Case "IT", "LN", "SJ": ws.Cells(r, "G").Value = ws.Cells(r, "G").Value / 100
Case "KK": ws.Cells(r, "G").Value = ws.Cells(r, "G").Value / 1000
End Select
Next r
With ws.Sort
.SortFields.Clear
.SortFields.Add2 Key:=ws.Range("C2:C" & ws.Range("A" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SortFields.Add2 Key:=Range("H2:H" & ws.Range("A" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Range("A1:H" & ws.Range("A" & Rows.Count).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

Fill blank cell value with non blank cell based another cell value

I have an issue with filling blank cells of a column.
I have 4 Column headings in A, B, C, D.
I am trying to create macro to fill blank cells for dynamic data as per attached Data able wherein cell value in Column D is randomly filled and blanked.. Blank cell value needs to filled based on value mentioned in Column A..
I have created the macro but it's working to fill the blank with above value only and not getting the exact result..
Can someone please help...
Below result is expected from coding...
Below is the macro which I have created
Sub FillblankCells()
lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
With Range("D2:D" & lr)
.SpecialCells(xlBlanks).FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
End Sub
A dictionary is probably overkill, but this should work.
Sub x()
Dim lr As Long, r As Range
Dim oDic As Object
lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
Set oDic = CreateObject("Scripting.Dictionary")
'store column A for each entry in D
For Each r In Range("D2:D" & lr).SpecialCells(xlCellTypeConstants)
oDic(r.Offset(, -3).Value) = r.Value
Next r
'retrieve each column A for blanks in D
For Each r In Range("D2:D" & lr).SpecialCells(xlCellTypeBlanks)
r.Value = oDic(r.Offset(, -3).Value)
Next r
End Sub
This appears to work, it's based on the values in column C.
Sub FillblankCells()
lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
With Range("D2:D" & lr)
.SpecialCells(xlBlanks).FormulaR1C1 = "=IF(R[-1]C[-1]<RC[-1], R[-1]C,R[1]C)"
.Value = .Value
End With
End Sub
You can sort the list before using your formula. Something like this might work:
Sub FillblankCells()
'Declarations.
Dim RngList As Range
Dim DblColumnQuote As Double
Dim DblColumnBuyerName As Double
'Setting.
Set RngList = Range("A1:D1")
DblColumnQuote = 1
DblColumnBuyerName = 4
'Resetting RngList.
Set RngList = Range(RngList, RngList.End(xlDown))
'Sorting RngList.
With RngList.Parent.Sort
.SortFields.Clear
.SortFields.Add Key:=RngList.Columns(DblColumnQuote), _
SortOn:=xlSortOnValues, _
Order:=xlDescending, _
DataOption:=xlSortNormal
.SortFields.Add Key:=RngList.Columns(DblColumnBuyerName), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange RngList
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
.SortFields.Clear
End With
'Filling the blank cells of the Buyer Name column in RngList.
With RngList.Columns(DblColumnBuyerName)
.SpecialCells(xlBlanks).FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
End Sub

Sort on font color using vba

I am trying to implement a button that, when pressed sorts an array first alphabetically, then based on font color. The column that I am using to sort has 3 possible values (enrolled, waitlisted, and cancelled). The font color for 'cancelled' is grey. I want to get enrolled at the top of the list, then waitlisted, then cancelled at the bottom. Shouldn't be that difficult, but I can't get the code to work. Here's the code I wrote. Many thanks!
Private Sub btnSort_Click()
Dim SortArray As Range
Dim SortColumn As Range
Set SortArray = Range("A3").CurrentRegion
Set SortColumn = Range(Range("A3").End(xlToRight), Range("A3").End(xlToRight).End(xlDown))
SortArray.Sort Key1:=SortColumn, Header:=xlYes
With SortArray.Sort
.SortFields.Clear
.SortFields.Add Key:=SortColumn
.xlSortOnFontColor
.SortOnValue.Color = RGB(192, 192, 192)
.SortOrder = xlAscending
.Header = xlYes
.Apply
End With
Since there are only 3 values, we use a helper column and then assign values to it. We then sort and then finally delete the helper column.
Let's say, your data looks like this
Try this code. I have commneted the code so you should not have a problem in understanding it.
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, lCol As Long
Dim rng As Range
Dim ColName As String
'~~> Change this to the relevant sheet
Set ws = Sheet1
With ws
'~~> Insert a helper column in Col A
.Columns(1).Insert Shift:=xlToRight
.Cells(1, 1).Value = "TmpHeader"
'~~> Get Last Row and last Column
'~~> I am assuming that headers are in row 1
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
lCol = .Cells(1, Columns.Count).End(xlToLeft).Column
ColName = Split(Cells(, lCol).Address, "$")(1)
'~~> Insert the formula in Col A
.Range("A2:A" & lRow).Formula = "=IF(RC[1]=""enrolled"",1,IF(RC[1]=""waitlisted"",2,3))"
'~~> Set your range
Set rng = .Range("A1:" & ColName & lRow)
'~~> Sort it
rng.Sort Key1:=.Range("A2"), Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
'~~> Delete the helper column
.Columns(1).Delete
End With
End Sub
When you run the above code, it inserts a helper column and then inserts a formula =IF(B2="enrolled",1,IF(B2="waitlisted",2,3)) What this basically does is assigns a value of 1,2 and 3 based on the value whether it is enrolled, waitlisted or cancelled.
Once the formula is inserted, we sort on Col A in ascending order and then finally delete the helper column.
Figured it out:
ActiveSheet.Range("A3").CurrentRegion.Sort Key1:=Range("I3"), Header:=xlYes
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add(Range("I3"), _
xlSortOnFontColor, xlDescending, , _
xlSortNormal).SortOnValue.Color = RGB(192, 192, 192)
With ActiveSheet.Sort
.SetRange Range("A3").CurrentRegion
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

Issues in VBA ".Apply"

Trying to make a dynamic sort macro, works on first column, then I get an error when I try to run on new column (trying to sort each column A-Z without changing the order of the other columns).
Sub SortCell()
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = ActiveSheet
Set StartCell = ActiveCell
ActiveCell.Columns("A:A").EntireColumn.Select
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:= _
ActiveCell, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveSheet.Sort
.SetRange ActiveCell.Range(StartCell, sht.Cells(LastRow, LastColumn))
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
MsgBox "Action complete.", vbInformation
End Sub
You're trying to work with the Sort code version that recording uses. This is very verbose and 'remembers' parameter values from previous operations. There is a much more concise syntax available that is just as effective.
dim c as long
with activesheet
for c=1 to .cells(1, .columns.count).end(xltoleft).column
if .cells(.rows.count, c).end(xlup).row >1 then
with .columns(c).Cells
.Sort Key1:=.cells(1), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlNo
end with
end if
next c
end with

Run-time error only after successful runs - Excel VBA

I have an Excel VBA macro that works successfully the first two times I run it, but the third time it gives this error:
Run-Time Error '1004'
The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.
If I restart Excel it works the first two times, then gives the error again. Why would this happen? Here's my code:
Dim rawData As Object
Dim report As Object
Dim areaCodes As Object
Set rawData = Sheets("RawData")
Set report = Sheets("Report")
Set areaCodes = Sheets("AreaCodes")
report.Cells.Clear
report.Cells.ClearFormats
stateCol = rawData.Cells(1, 1).EntireRow.Find(What:="state", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
Dim MyRange As Range
Set MyRange = rawData.Cells(1, stateCol)
With rawData
lastRow = .Cells(Rows.Count, MyRange.Column).End(xlUp).Row
.Range(.Cells(2, stateCol), .Cells(lastRow, stateCol)).Copy
End With
With report
.Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Range(.Cells(3, 1), .Cells(lastRow + 1, 1)).RemoveDuplicates Columns:=1, Header:=xlNo
End With
lastRow = report.Cells(Rows.Count, Range("A1").Column).End(xlUp).Row
report.Range("B3").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(rawData!C[" & stateCol - 2 & "],report!RC[-1])"
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
Range("B" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C3").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/R" & lastRow + 1 & "C[-1]"
Range("C3").AutoFill Destination:=Range("C3:C" & lastRow)
Range("C" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C:C").NumberFormat = "0.0%"
Range("A2:A" & lastRow + 1).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
report.Range("A2").Value = "State"
report.Range("A2").Font.Bold = True
report.Range("A:A").HorizontalAlignment = xlCenter
report.Range("A3").FormulaR1C1 = "=INDEX(areaCodes!R2C5:R52C5,MATCH(report!RC[1],AreaCodes!R2C6:R52C6,0))"
Range("A3").Select
ActiveCell.AutoFill Destination:=Range("A3:A" & lastRow)
With report
newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
.Range(.Cells(3, 3), .Cells(newLastRow, 3)).Copy
.Range("C3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End With
With report
.Sort.SortFields.Add Key:=Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
With .Sort
.SetRange Range("A2:D" & newLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
you should qualify the range in your sort instruction, this will produce an error if the sheet report is not activated
With report
.Sort.SortFields.Add Key:=.Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
newLastRow = .Cells(Rows.Count, .Range("C1").Column).End(xlUp).Row - 1
With .Sort
.SetRange report.Range("A2:D" & newLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With

Resources