Preamble: I have a problem and I've got a very simple solution that I'm using. However, I was wondering, for the sake of learning, if any Excel Guru's out there had an alternate solution to my problem.
I have an excel table with a column that contains about 4500 U.S. and Canadian cities. Here’s a sample of the way the data in the column is formatted:
- Toronto, ON
- Jacksonville, FL
- VANCOUVER, BC
On another sheet in the workbook, I randomly select a City.
So I’m using the following function:
=INDEX(DATA!$E$2:$E$4576,RANDBETWEEN(1,4574),1)
This function produces a random selection from the 4500 cities; the problem is that I want to populate two cells, one that has the City and one that has the Province/State.
Typically, extracting the City/Province from a cell formatted ‘City, Province’ is pretty straight forward.
I’d do something like this:
For the State or Province:
=RIGHT(A1,2)
For the City:
=LEFT(A1,LEN(A1)-4)
My problem lies in the random selection of the city/state.
I can’t select the city using:
=LEFT(INDEX(DATA!$E$2:$E$4576,RANDBETWEEN(1,4574),1),LEN(INDEX(DATA!$E$2:$E$4576,RANDBETWEEN(1,4574),1))-4)
Because when I’m calculating the LEN function, it randomly selects another city and uses that length for the calculation. So depending on the combination of random city selections in the one function, some will be short, some will be long (and some will be accurate).
An extension of the same problem is when I do the RIGHT string function to get the state, that'll be from another randomly selected value, so it won't (necessarily) match the city.
The simplest thing I could think of, and it's what I've done, is to make the random selection in one cell, then perform the RIGHT and LEFT functions on that cell.
Like this:
//populate cell A1 randomly
A1=INDEX(DATA!$E$2:$E$4576,RANDBETWEEN(1,4574),1)
//pull the province/state form A1
B1=RIGHT(A1,2)
//pull the city name from cell A1
C1=LEFT(A1,LEN(A1)-4)
I'm just curios if there's another way of doing the LEFT/LEN function on the RANDOM selection without having to play off of another cell. I'd like to avoid VBA if possible. It's possible there isn't a solution, but I'm hoping someone who knows more than I do will have some ideas!