VBA dim and set clarification

B-Man

Board Regular
Joined
Dec 29, 2012
Messages
183
Office Version
  1. 2019
Platform
  1. Windows
why is it if I try to set my work book or work sheets I cant use the set shortcut in my commands...
see below


VBA Code:
 Sub test()


    Dim wb As Workbook
    Dim ws As Worksheet
    Dim myrange As Range
    
 
    Set wb = ActiveWorkbook
    Set ws = Worksheets("sheet1")
    
Set myrange = wb.ws.Range("K2:K15")     'doesn't work
Set myrange = ActiveWorkbook.Worksheets("sheet1").Range("K2:K15")   'does work
    
        With wb.ws.Range("K2:K15")  'doesn't work
        With myrange                'does work
        .FormatConditions.Delete
        .FormatConditions.AddUniqueValues
        .FormatConditions(1).DupeUnique = xlDuplicate
        .FormatConditions(1).Font.Color = -16776961
        .FormatConditions(1).Font.Bold = True
    End With

 End Sub
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
It should be like
VBA Code:
    Set wb = ActiveWorkbook
    Set ws = wb.Worksheets("sheet1")
    
Set myrange = ws.Range("K2:K15")
 
Upvote 0
Solution
Or just avoiding any useless object variable :​
VBA Code:
 Sub Test1()
    With ActiveWorkbook.Worksheets("Sheet1").[K2:K15]
        .FormatConditions.Delete
        .FormatConditions.AddUniqueValues
        .FormatConditions(1).DupeUnique = xlDuplicate
        .FormatConditions(1).Font.Color = -16776961
        .FormatConditions(1).Font.Bold = True
    End With
 End Sub
 
Upvote 0

Forum statistics

Threads
1,214,846
Messages
6,121,905
Members
449,054
Latest member
luca142

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top