简体   繁体   中英

Excel Macro or Function: Populate a cell range (Column A) with a looped values (from another sheet) if cell is not blank

Need help for someone trying to learn macro coding.

Sheet 1 has two Columns A & B. Sheet 2, Col A has a range of value. I wanted to fill Sheet 1 Column B with a value on Sheet 2 Column A if Sheet 1 Column A cell is not empty.

Illustration below.

Sheet2 Col A
Brian, 
David,
Nicole,
Aspen,

Col A                  
Apple         
Banana        
Orange        
Lemon         
Mango         
Strawberry    
Grape      

Col B should get filled by looping with the names, Brian for Apple and then David for Banana, and so on and then go back to David and so on until Grape for Nicole..

Please help provide with a function or macro vba code to accomplish this.

One way is to use INDIRECT :

=INDIRECT("Sheet2!A" & MOD(ROW()+3,4)+1)

This assumes the names are in A1:A4

Edit: and I just thought of a way to use INDEX instead:

=INDEX(Sheet2!A$1:A$4,MOD(ROW()+3,4)+1)

MOD will return the remainder of the row number divided by n (in this case, 4 ). This will result in a number between 0 and 3 ( n-1 ), inclusively. the sequence for rows 1-6 is 1, 2, 3, 0, 1, 2 .

By adding 3 ( n-1 ) to the row number, I can get the sequence for rows 1-6 to become 0, 1, 2, 3, 0, 1

Then adding 1 to the mod makes the sequence: 1, 2, 3, 4, 1, 2 , which I can then use as the index for the table of names

For 12 names you will want to use:

=INDEX(F$1:F$12,MOD(ROW()+11,12)+1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM