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

TheRedCardinal

Board Regular
Joined
Jul 11, 2019
Messages
243
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

Which came first: VisiCalc or Lotus 1-2-3?
Dan Bricklin and Bob Frankston debuted VisiCalc in 1979 as a Visible Calculator. Lotus 1-2-3 debuted in the early 1980's, from Mitch Kapor.
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,215,110
Messages
6,123,148
Members
449,098
Latest member
Doanvanhieu

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