VBA - Need formula to work on dynamic column - But getting a variable error

TheRedCardinal

Active Member
Joined
Jul 11, 2019
Messages
252
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
Hi all,

I have a simple Sub that replaces one value in a cell with another from a lookup table. It loops around the length of the column replacing row by row

Code:
Sub UpdateCountry()

Dim lr As Long, i As Long
Dim CountryCol As Range
Dim x As Variant


    Set ws1 = Sheets("2. Final Data")
    ws1.Select
    
    lr = Range("A1").End(xlDown).Row
    
    With ws1
    
        CountryCol = .Range("A1:Z1").Find("Country/region")
    
    End With
    
    For i = 1 To lr
        x = Application.VLookup(Cells(i, CountryCol), Sheets("Data Sheet").Columns("A:B"), 2, False)
        If Not (IsError(x)) Then
            Cells(i, CountryCol).Value = x
        End If
    
    Next i


End Sub

I get an "Object Variable or With Block variable not set" error highlighting the line between With WS1 and End With.

CountryCol Variable is clearly declared within the Sub; WS1 is declared as a worksheet in the Public section of the module.

The text it is looking for is definitely there too.

I have missed something obvious - so can anybody spot it?

Thanks!
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
As the variable is an object (in this case a range) when you assign a value to it you need to precede it with Set like
Code:
Set CountryCol = .Range("A1:Z1").Find("Country/region")
 
Upvote 0
You're welcome & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,021
Latest member
Justyna P

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