I'm trying to go go through columns and highlight duplicates within the columns.
I used record macro to get an idea of what I need but I'm not sure how to apply this across many columns. Highlighting all columns won't work because many of the names repeat. I need to find out if a name repeats multiple times within a list.
This is the code I have so far:
Sub findDuplicates()
Application.Goto Reference:="R3C18:R89C18"
Application.Goto Reference:="R3C18:R88C18"
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Font
.Color = -16751204
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 10284031
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("R21").Select
End Sub
This is code I have that goes through each column within my range from B3:OA3 and sorts by color and alphabet. My thinking is that because this code goes column by column and sorts, I could simply add to it to highlight duplicates within the column it was already sorting. But I'm not sure how'd I'd do that.
Sub sortColorThenAlpha()
'sort by color then by alphabet
Dim rngFirstRow As Range
Dim rng As Range, rngSort As Range
Dim ws As Worksheet
Application.ScreenUpdating = False
Set ws = ActiveSheet
Set rngFirstRow = ws.Range("B3:OA3")
For Each rng In rngFirstRow.Cells
With ws.Sort
Set rngSort = rng.Resize(86, 1) 'to row 88
.SortFields.Clear
.SortFields.Add(rng, xlSortOnCellColor, xlAscending, , xlSortNormal). _
SortOnValue.Color = RGB(198, 239, 206)
.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.SetRange rngSort
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next rng
Application.ScreenUpdating = True
End Sub
This is what I'm looking at. That yellow conditinal formatting is what I'm trying to apply to each column between row 3 and 88.
VBA does not seem necessary as Conditional Formatting with the following rules seems to work:
=A1=VLOOKUP(A1,A2:A$99,1,FALSE) Applies to: =$A$1:$J$99
=A2=VLOOKUP(A2,A$1:A1,1,FALSE) Applies to: =$A$2:$J$99
with references adjusted to suit.
If I understand your question correctly, you want to be able to highlight duplicates in a single column, and you want to be able to automatically apply this formatting to all columns in a given sheet. So if Cleopatra appears once in several columns, she won't be highlighted, but if she appears more than once in a single column, she will.
The following code does just that. I'm finding the last column by looking for a value in row 3.
Sub HighlightDupesOneColumnAtATime()
Dim ws As Worksheet
Dim myColumn As Long
Dim i As Integer
Dim columnCount As Long
Dim lastRow As Long
Dim dupeColor As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
columnCount = ws.Cells(3, ws.Columns.Count).End(xlToLeft).Column
dupeColor = 9944516
For i = 1 To columnCount
lastRow = ws.Cells(ws.Rows.Count, i).End(xlUp).Row
Call HighlightDupesInRange(dupeColor, Cells(1, i).Resize(lastRow, 1))
' it is easy to change the color of the
' highlighted duplicates if you want
dupeColor = dupeColor + 15
Next i
End Sub
Sub HighlightDupesInRange(cellColor As Long, rng As Range)
With rng
.FormatConditions.Delete
.FormatConditions.AddUniqueValues
.FormatConditions(1).DupeUnique = xlDuplicate
.FormatConditions(1).Interior.Color = cellColor
.FormatConditions(1).StopIfTrue = False
End With
End Sub
Related
I need Excel to detect the last column I have and sort on that column. I have a macro that generates a new column every time it is used so I cannot use a constant.
Sub sortyness()
Dim sortdata(A1 & ":", Cells(LastRow, LastColumn)) As Range
ActiveWorkbook.Worksheets("Compiled").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Compiled").Sort.SortFields.Add _
Key:=Range(Sorton), Sorton:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Compiled").Sort
.SetRange Range(sortdata)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Here's a screenshot of the sheet:
I am having trouble with getting it to sort by the last column. Can I define the column by looking for the first cell in row 1 that has no data and then use that as a basis to sort? How should I modify my VBA?
Thank you.
I don't know how to edit this thing to get it to not appear as a duplicate, but it's obviously not a duplicate. Mine is more concerned with running a macro on the last column than it is finding the last column.
An vba sort operation actually requires much less code than you get from a recording.
Dim sortdata As Range, LastRow as long, LastColumn as long
With ActiveWorkbook.Worksheets("Compiled")
LastRow = .cells(.rows.count, "A").end(xlup).row
LastColumn = .cells(1, .columns.count).end(xltoleft).column
with .range(.cells(1, 1), .Cells(LastRow, LastColumn))
.Cells.Sort Key1:=.Columns(.columns.count), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlyes
end with
end with
Concerning the second line here:
Dim sortdata(A1 & ":", Cells(LastRow, LastColumn)) As Range
This is not how you assign range. If you want to assign a range, starting on A1 and ending on lastRow, lastColumn, consider this:
Public Sub TestMe()
Dim lastRow As Long: lastRow = 5
Dim lastCol As Long: lastCol = 10
Dim sortData As Range
Set sortData = Range("A1:" & Cells(lastRow, lastCol).Address)
Debug.Print sortData.Address
End Sub
In the above case the range is assigned to the ActiveSheet, which is not always what you may need. If you want to avoid assigning to the ActiveSheet, you should specify the worksheet as well:
With Worksheets("Compiled")
Set sortData = .Range("A1:" & .Cells(lastRow, lastCol).Address)
End With
The two dots in the code above .Range and .Cells will make sure that you refer to the Worksheets("Compiled") and thus will save some problems in the future.
Sort the "last" column with a single line of VBA:
Columns(ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count)._
Column).Sort key1:=Columns(ActiveSheet._
UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column)
...which is exactly the same as:
Sub SortLastColumn()
With ActiveSheet.UsedRange
Columns(.Columns(.Columns.Count).Column).Sort key1:=Columns(.Columns(.Columns.Count).Column)
End With
End Sub
I have a script that changes the cell color and a script to hide the cells that are not colored. The hide script works, but it hides ALL the cells, even the colored ones. I noticed that when I use the script that changes the cell color, it does not detect the changes in the excel interface(in the 'Fill Color' settings in 'Home' tab, under the 'font size' selection). I also noticed that when try to change the color of the cells (using the excel interface) that are colored from using the script, it does not change (the color seems to be fixed to whatever is set from the script).
Therefore, it seems like the interface does not detect the changes that are being made using the coloring script.
Also, I noticed the script below takes a while to check/hide all the cells. If there is a way to speed up the process, that would be great!
Any help will be greatly appreciated!
Thank you!
The script to hide uncolored cells:
Public Sub HideUncoloredRows()
Dim startColumn As Integer
Dim startRow As Integer
Dim totalRows As Integer
Dim totalColumns As Integer
Dim currentColumn As Integer
Dim currentRow As Integer
Dim shouldHideRow As Integer
startColumn = 1 'column A
startRow = 1 'row 1
totalRows = Sheet1.Cells(Rows.Count, startColumn).End(xlUp).Row
For currentRow = totalRows To startRow Step -1
shouldHideRow = True
totalColumns = Sheet2.Cells(currentRow, Columns.Count).End(xlToLeft).Column
'for each column in the current row, check the cell color
For currentColumn = startColumn To totalColumns
'if any colored cell is found, don't hide the row and move on to next row
If Not Sheet1.Cells(currentRow, currentColumn).Interior.ColorIndex = -4142 Then
shouldHideRow = False
Exit For
End If
Next
If shouldHideRow Then
'drop into here if all cells in a row were white
Sheet2.Cells(currentRow, currentColumn).EntireRow.Hidden = True
End If
Next
End Sub
The script that changes the color certain cells:
Range("A8").Select
Application.CutCopyMode = False
Range("A8").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=COUNTIF(Name_Preps,A8)=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3 'Changes the cell to green
.TintAndShade = 0.4
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Try to change your condition to follow
For currentColumn = startColumn To totalColumns
'if any colored cell is found, don't hide the row and move on to next row
If Sheet1.Cells(currentRow, currentColumn).Interior.ThemeColor = xlThemeColorAccent3 Then
shouldHideRow = False
Exit For
End If
Next
conditional formatting is not detected by Interior.ColorIndex and the likes
if you want to go on that way you can see here or here for relevant code
but I'd abandon conditional formatting as well as Select/Selection/Activate/ActiveXXX pattern and go simply this way:
Option Explicit
Sub HandleRowsColorAndVisibility()
Dim iRow As Long
With Range("A8", Cells(Rows.count, 1).End(xlUp)) '<--| reference cells from A8 down to column A last not empty cell
ResetRange .Cells '<--| first, bring range formatting and visibility back to a "default" state
For iRow = .Rows.count To 1 Step -1 '<--| then start looping through range
If WorksheetFunction.CountIf(Range("Name_Preps"), .Cells(iRow, 1)) = 1 Then '<-- if current cell matches your criteria ...
FormatRange .Cells(iRow, 1), True, False, 0, xlColorIndexAutomatic, xlThemeColorAccent3, 0.4 '<--| then format it
Else '<--| otherwise...
.Rows(iRow).Hidden = True '<--| hide it!
End If
Next
End With
End Sub
Sub ResetRange(rng As Range)
rng.EntireRow.Hidden = False
FormatRange rng, False, False, 0, xlColorIndexAutomatic, -4142, 0
End Sub
Sub FormatRange(rng As Range, okBold As Boolean, okItalic As Boolean, myFontTintAndShade As Single, myPatternColorIndex As XlColorIndex, myInteriorThemeColor As Variant, myInteriorTintAndShade As Single)
With rng
With .Font
.Bold = okBold
.Italic = okItalic
.TintAndShade = myFontTintAndShade
End With
With .Interior
.PatternColorIndex = myPatternColorIndex
.ThemeColor = myInteriorThemeColor
.TintAndShade = myInteriorTintAndShade
End With
End With
End Sub
I would like to implement an Excel macro that sorts all columns from column "C" to the last column containing data (columns A and B shall not be affected).
The columns shall be sorted from A->Z based on the cell value of their first row (which is a string).
So far, I came up with the following code which I do not like that much because it contains hardcoded numbers for the Sort range making the code not really robust.
Sub SortAllColumns()
Application.ScreenUpdating = False
'Sort columns
With ActiveWorkbook.Worksheets("mySheet").Sort
.SetRange Range("C1:ZZ1000")
.Header = xlYes
.MatchCase = False
.Orientation = xlLeftToRight
.Apply
End With
Application.ScreenUpdating = True
End Sub
Searching the internet, one may find tons of suggestions getting the last used column or row. However most of them will blow up the code more than I expected.
I am not a VBA expert and it would be great if someone could make a suggestion how this problem can be solved in an elegant and efficient way.
If this is important: We will definitely not have more that 1000 rows and 1000 columns.
Any suggestion is highly appreciated.
edited:
changed temporary sheet adding statement to have it always as the last one
revised its deletion statement accordingly
should your need be to sort columns by moving them so as to have their headers sorted from left to right, then try this code
Option Explicit
Sub main()
Dim lastCol As Long
With Sheets("mySheet")
lastCol = .cells(1, .Columns.Count).End(xlToLeft).Column
Call OrderColumns(Range(.Columns(3), Columns(lastCol)))
End With
End Sub
Sub OrderColumns(columnsRng As Range)
Dim LastRow As Long
With columnsRng
LastRow = GetColumnsLastRow(columnsRng)
With .Resize(LastRow)
.Copy
With Worksheets.Add(after:=Worksheets(Worksheets.Count)).cells(1, 1).Resize(.Columns.Count, .Rows.Count) 'this will add a "helper" sheet: it'll be removed
.PasteSpecial Paste:=xlPasteAll, Transpose:=True
.Sort key1:=.Columns(1), Order1:=xlAscending, Orientation:=xlTopToBottom, Header:=xlNo
.Copy
End With
.PasteSpecial Paste:=xlPasteAll, Transpose:=True
Application.DisplayAlerts = False: Worksheets(Worksheets.Count).Delete: Application.DisplayAlerts = True 'remove the "helper" sheet (it's the (n-1)th sheet)
End With
End With
End Sub
Function GetColumnsLastRow(rng As Range) As Long
Dim i As Long
'gets last row of the given columns range
GetColumnsLastRow = -1
With rng
For i = 1 To .Columns.Count
GetColumnsLastRow = WorksheetFunction.Max(GetColumnsLastRow, .Parent.cells(.Parent.Rows.Count, .Columns(i).Column).End(xlUp).row)
Next i
End With
End Function
it makes use of a "helper" temporary (it gets deleted by the end) sheet.
Thanks to the suggestions and revisions of #SiddharthRout I got this:
Sub SortAllColumns()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim LastColumnLetter As String
Set ws = ThisWorkbook.Sheets("mySheet")
'Get range
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastColumnLetter = Split(.Cells(, LastColumn).Address, "$")(1)
'Sort columns
Range("C1:" & LastColumnLetter & LastRow).Select
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=Range("C1:" & LastColumnLetter & 1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With .Sort
.SetRange ws.Range("C1:" & LastColumnLetter & LastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlLeftToRight
.Apply
End With
End With
Application.ScreenUpdating = True
End Sub
So I'm sorting this Excel worksheet in rows alphabetically, avoiding the first few columns. This is my code. Somehow it worked perfectly, sorting rows that go from maybe 20 or 30 cells, to ones with hundreds. Each row has a different number of cells. But it sorted every cell except the last one. The last cell is some random one that comes after the ones beginning in "z", but starts with say, a "P", or an "L".
Here's my code:
Sub SortRows()
Dim lngIndex As Long
Dim strArray(9 To 11000) As String
Dim intCounter As Integer
Dim sht As Worksheet, rng As Range
Set sht = ActiveWorkbook.Worksheets("Page1")
Set rng = sht.Range("J10:UN10")
intCounter = 1
For lngIndex = LBound(strArray) To UBound(strArray)
intCounter = intCounter + 1
strArray(lngIndex) = intCounter
With sht.Sort
.SortFields.Clear
.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.SetRange rng
.Header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
Set rng = rng.Offset(1, 0)
Next
End Sub
Tested your code and it works fine. Try put codes into a new worksheet and test.
i'm trying to tweak my macro so that it creates a column next to a specific column that always changes positions. In the macro i have below, it is just an absolute reference of 6 columns to the left. However, this wont always be the case. Should I set this up by finding the column name in the top row?
Basically the macro creates a new column and puts in an IF statement if it is a duplicate, and then sets up conditional formatting to highlight all the values of "1". Sorry if i am not explaining this clearly!
Sub test()
Columns("L:L").Select
Selection.Insert Shift:=xlToRight
Range("L2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-6]=R[-1]C[-6],R[-1]C+1,1)"
Range("L2").Select
Selection.Copy
Range("K2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
I have a working code for this but it requires that your data be in a table. This is the best way to dynamically manipulate and reference the data (Columns, Rows, etc..)
Also I heavily rely on the ListObject method. It really handles tables well.
Public Sub InsertColumn(Optional columnName As String, Optional BeforeORAfter As String)
Dim loTableName As ListObject
Dim loColumn As ListColumn
Dim newColDest As Long
'Handles user input if they desire the column inserted before or after
Select Case UCase(BeforeORAfter)
Case Is = "BEFORE"
newColDest = 0 'Inserts column and moves reference column right
Case Else
newColDest = 1 'Inserts column to the right of reference column
End Select
'Ensures the user selects a reference column name
Select Case columnName
Case Is = ""
columnName = InputBox("Enter column name to be referenced.", "Enter Column Name")
Case Else
End Select
'Sets the ListObject as the table.
Set loTableName = Range("TableName").ListObject
With loTableName
On Error GoTo InsertError 'Exits sub in case the column couldn't be found
.ListColumns.Add (.ListColumns(columnName).Index + newColDest)
End With
Exit Sub
InsertError:
'Most likely error is user typed the column header incorrectly.
MsgBox "Error creating column. Ensure a correct reference column was chosen", vbExclamation + vbOKOnly, "Insert Error"
End Sub
Any questions or problems, just let me know.
This below would be something you can work with (it will ask the column to search and perform the actions in your recorded macro...
Check my website http://multiskillz.tekcities.com/k2500_0vbaMenu.html
Sub test_modified()
'worksheet workbook object
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
'range object to select a column
Dim fRng As Variant
fRng = Application.InputBox(Prompt:="value to find", Title:="InputBox Method", Type:=2)
'range object to find the column
Dim colRng As Range
Set colRng = ws.Rows(1)
'find column
Dim fcol As Range
Set fcol = colRng.Find(fRng, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
'convert the column address to a number
Dim colNb As Byte
colNb = fcol.Column
'going on from your recorded macro
'Columns("L:L").Select
ws.Columns(colNb).Select
Selection.Insert Shift:=xlToRight
Range("L2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-6]=R[-1]C[-6],R[-1]C+1,1)"
Range("L2").Select
Selection.Copy
Range("K2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Cheers
Pascal