• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

How to Apply Conditional Formatting on a Variably Sized Range VBA|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / How to Apply Conditional Formatting on a Variably Sized Range VBA|VBA & Macros|Excel Forum|My Online Training Hub
Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search|Last Search Results
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosHow to Apply Conditional Formatting…
sp_PrintTopic sp_TopicIcon
How to Apply Conditional Formatting on a Variably Sized Range VBA
Avatar
Stephanie Lim
Member
Members
Level 0
Forum Posts: 7
Member Since:
July 4, 2018
sp_UserOfflineSmall Offline
1
July 12, 2018 - 12:05 pm
sp_Permalink sp_Print

Hi!

I'm trying to write a code where I want to check for duplicate values in two non-contiguous columns on the same worksheet in Excel. The size of the columns however always changes depending on how many accounts there are for the year. For instance, some years there may only be 10 accounts while in other years there may be 15 accounts.

I tried to code to allow for the range of cells to be selected to change but everytime I run my code the error: 'Run-time error 1004: Application-defined or Object-defined error' will pop up.

This is my code:

Sub RepeatedAccs()
'
' this macro identifies the duplicated accs across both years
'
    ' duplicates Analysis sheet and renames it to Repeated Accs
    Worksheets("Analysis").Copy After:=Sheets("Analysis")
    Sheets("Analysis (2)").Name = "Repeated Accs (2)"
   
    Dim Cell As Range
    Dim lastrow As Long
    Dim twentyP As Variant
    Dim eightP As Variant ' if declared As Integer, overflow error will occur i.e. result is too large to be represented
    Dim a As Variant
   
    lastrow = Cells(rows.Count, "C").End(xlUp).Row
    a = Sheets("Analysis").Range("C5:C" & lastrow)
    twentyP = WorksheetFunction.Percentile_Exc(a, 0.2)
    eightP = WorksheetFunction.Percentile_Exc(a, 0.8)
    Range("C5:C" & lastrow).Select
   
    With Sheets("Repeated Accs (2)")
       
        ' For Each Cell In .Range("C5:C" & .Cells(.rows.Count, "C").End(xlUp).Row)
        For Each Cell In Selection
            If Cell.Value >= twentyP And Cell.Value <= eightP Then
                ' a = Sheets("Repeated Accs (2)").Cells(Rows.Count, "C").End(xlUp).Row
                .rows(Cell.Row).ClearContents
                ' cannot delete cell because cell position will change
            End If
        Next
        Selection.SpecialCells(xlCellTypeBlanks).Select
        Selection.EntireRow.Delete
       
    End With
   
    With Sheets("Repeated Accs (2)")
        .Cells.FormatConditions.Delete 'deletes all conditional formatting rules i.e. top & bottom 20th percentile
    End With
   
    ' On Error Resume Next
    ' ActiveWorkbook.Worksheets("Repeated Accs (2)").Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    ' On Error GoTo 0
    '' Not enough memory for above code??
   
    ' ' Sort Abs Diff tables fm smallest to largest value
    Dim frow As Long
    frow = Cells(rows.Count, "A").End(xlUp).Row
    Range("A5:C" & frow).Sort key1:=Range("A5:A" & frow), order1:=xlAscending, Header:=xlNo

    ' ' Sort % Diff tables fm smallest to largest value
    Dim lrow As Long
    lrow = Cells(rows.Count, "E").End(xlUp).Row
    Range("E5:G" & lrow).Sort key1:=Range("E5:E" & lrow), order1:=xlAscending, Header:=xlNo
           
    ' ' Check for duplicate values
    Dim b As Variant, c As Variant
    Dim y As Variant
    Set b = Sheets("Repeated Accs (2)").Range("A5:A" & frow)
    Set c = Sheets("Repeated Accs (2)").Range("E5:E" & lrow)
    Set y = Application.Union(b, c)
    With Sheets("Repeated Accs (2)")
        .Range(y).Parent.Select
    End With
    Range("E5").Activate
    Selection.FormatConditions.AddUniqueValues
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).DupeUnique = xlDuplicate
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 13551615
        .TineAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False
   
End Sub

The underlined portion is where the error occurs.

Can anyone tell me what's wrong and how I can fix it?

Thanks a million!

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
2
July 12, 2018 - 3:52 pm
sp_Permalink sp_Print

Hi Stephanie

Can you attach your file with some sample data so that we can see what you are trying to check.

It will give a clearer picture.

Sunny

Avatar
Stephanie Lim
Member
Members
Level 0
Forum Posts: 7
Member Since:
July 4, 2018
sp_UserOfflineSmall Offline
3
July 12, 2018 - 5:30 pm
sp_Permalink sp_Print

Hi Sunny,

Attached is the sample data.

Basically what I'm trying to do is to compare the account codes in Cols A and E and see which account/value appears twice (i.e. duplicate values). The thing is the number of accounts is always changing for each analysis. For example, in this template, there are 7 accounts (rows 5 - 11) only across both criteria.

However, in the next analysis being done, there could be 10 accounts. Hence, I wrote the code:

' ' Sort Abs Diff tables fm smallest to largest value
    Dim frow As Long
    frow = Cells(rows.Count, "A").End(xlUp).Row
    Range("A5:C" & frow).Sort key1:=Range("A5:A" & frow), order1:=xlAscending, Header:=xlNo

    ' ' Sort % Diff tables fm smallest to largest value
    Dim lrow As Long
    lrow = Cells(rows.Count, "E").End(xlUp).Row
    Range("E5:G" & lrow).Sort key1:=Range("E5:E" & lrow), order1:=xlAscending, Header:=xlNo
           
    ' ' Check for duplicate values
    Dim b As Variant, c As Variant
    Dim y As Variant
    Set b = Sheets("Repeated Accs (2)").Range("A5:A" & frow)
    Set c = Sheets("Repeated Accs (2)").Range("E5:E" & lrow)

What I wanted to achieve was to:

1. Select the range w the account codes in Col A & E (up to the last non-empty cell)

2. Apply conditional formatting for duplicate values on the 2 selected non-contiguous ranges.

 

I hope I managed to explain it better! Thanks so much for the help.

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
4
July 13, 2018 - 1:06 am
sp_Permalink sp_Print

Hi Stephanie

Try replacing 

With Sheets("Repeated Accs (2)")
        .Range(y).Parent.Select
End With

with 

Union(b, c).Select

Hope this helps

Sunny

Avatar
Stephanie Lim
Member
Members
Level 0
Forum Posts: 7
Member Since:
July 4, 2018
sp_UserOfflineSmall Offline
5
July 13, 2018 - 1:00 pm
sp_Permalink sp_Print

Hi Sunny,

Yes it works, thanks!

Can I understand why it won't work with my original code though (for learning purposes)? Why can't I assign Union(b, c).Select to a variable like y first and select it thereafter?

Thanks!

Stephanie

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
6
July 13, 2018 - 2:24 pm
sp_Permalink sp_Print

Hi Stephanie

Thanks for your feedback. Glad to know it is working for you.

The only explanation i can think of is the code you used is not correct Laugh

Sunny

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 245
Currently Online:
Guest(s) 9
Top Posters:
SunnyKow: 1432
Anders Sehlstedt: 870
Purfleet: 412
Frans Visser: 346
David_Ng: 306
lea cohen: 219
A.Maurizio: 202
Jessica Stewart: 202
Aye Mu: 201
jaryszek: 183
Newest Members:
michael serna
mashal sana
Tiffany Kang
Leah Gillmore
Sopi Yuniarti
LAFONSO HERNANDEZ
Hayden Hao
Angela chen
Sean Moore
John Chisholm
Forum Stats:
Groups: 3
Forums: 24
Topics: 6215
Posts: 27248

 

Member Stats:
Guest Posters: 49
Members: 31897
Moderators: 3
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: MOTH Support, Velouria, Riny van Eekelen
© Simple:Press —sp_Information

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.