Link to home
Start Free TrialLog in
Avatar of paulpp
paulppFlag for United States of America

asked on

Fastest Way Change Value of Cell in Excel Based on Another Sheet VBA

Hello Everyone,

I have a sheet named "Pull" with zip codes pulled from my database in Column A.  The other sheet I have named "Zips" has every zip code in the United States in Column A - and the City Name in Column B.  I want to create code that will replace the zip code in Column A of sheet "Pulls" with the City name from the sheet named "Zips".  

I know I can use find and replace, or if statments, but I am looking for a way that will not bog down the program seeing as there are more than 42000 zip codes in the sheet "Zips".  Thank you.
Avatar of dandraka
dandraka
Flag of Greece image

Could you use a lookup function? have the data in a separate sheet
ASKER CERTIFIED SOLUTION
Avatar of byundt
byundt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The first formula took about 1 second on my laptop to determine 42,000 randomly chosen city names using Excel 2003. The second formula took 25 seconds.

Here is a macro that automates the first formula. After the formulas have calculated, they are replaced with the values returned. Remember that it has the limitation of requiring the Zips worksheet to be sorted by column A and for it to contain a complete list. You'll get errors if either condition is not satisfied 100% of the time!

This macro should be installed in a regular module sheet, as shown in the sample workbook. This workbook is somewhat large, so be patient while it downloads.
Sub GetCityNames()
Dim rg As Range, rgZIPtable As Range
Set rgZIPtable = Worksheets("Zips").Range("A1")     'First ZIP number in ZIP table
Set rgZIPtable = Range(rgZIPtable, rgZIPtable.Worksheet.Cells(Rows.Count, rgZIPtable.Column).End(xlUp)).Resize(, 2)     'The complete table, including city names
Set rg = Range("A1")    'First ZIP number in active worksheet
Set rg = Range(rg, Cells(Rows.Count, rg.Column).End(xlUp)).Resize(, 2)      'The complete Pull list, including space for city names
Application.ScreenUpdating = False
rg.Columns(2).Formula = "=VLOOKUP(" & rg.Cells(1, 1).Address(False, False) & "," & rgZIPtable.Address(external:=True) & ",2)"
rg.Columns(2).Formula = rg.Columns(2).Value     'Replace the formula with the value
Application.ScreenUpdating = True
End Sub

Open in new window

GetZipsQ25878580.xls