I am trying to find the value of "meas_value" (time point for meas value "RECORDED_TIME") at the closest time point to each time the patient has hypoxia (hypoxia_55_date#) I am able to do it with the code below, but I need to do this for up to 50 episodes per person with hypoxia and therefore I would like to create a loop instead of repeating this over and over.

gen diff6 = hypoxia_55_date6 - RECORDED_TIME

******6th hypoxia************
bysort person_id: generate absgap6 = abs(diff_6) if abs(diff_6)<=1
bysort person_id (absgap6 diff_6): gen MAP_HH6_count = _n
bysort person_id (absgap6 diff_6): gen nearestMAP_HH6 = meas_value if MAP_HH6_count==1
sort person_id nearestMAP_HH6
by person_id: fillmissing nearestMAP_HH6, with(first)
bysort person_id (absgap6 diff_6): gen disMAP_HH6 = absgap6 if MAP_HH6_count==1
sort person_id disMAP_HH6
by person_id: fillmissing disMAP_HH6, with(first)
order person_id hypoxia_55_date6 absgap6 nearestMAP_HH6 disMAP_HH6 meas_value diff_6

gen HH6_60 = 1 if nearestMAP_HH6 <60 & hypoxia_55_date6 !=.
sort person_id HH6_60
by person_id: fillmissing HH6_60, with(first)
replace HH6_60 = 0 if HH6_60 ==. & hypoxia_55_date6 !=.
tab HH6_60 if MAP_amount ==1
count if hypoxia_55_date6 !=. & MAP_amount ==1

******7th hypoxia************
bysort person_id: generate absgap7 = abs(diff_7) if abs(dif_7)<=1
bysort person_id (absgap7 dif_7): gen MAP_HH7_count = _n
bysort person_id (absgap7 dif_7): gen nearestMAP_HH7 = meas_value if MAP_HH7_count==1
sort person_id nearestMAP_HH7
by person_id: fillmissing nearestMAP_HH7, with(first)
bysort person_id (absgap7 dif_7): gen disMAP_HH7 = absgap7 if MAP_HH7_count==1
sort person_id disMAP_HH7
by person_id: fillmissing disMAP_HH7, with(first)
order person_id hypoxia_55_date7 absgap7 nearestMAP_HH7 disMAP_HH7 meas_value dif_7

gen HH7_60 = 1 if nearestMAP_HH7 <60 & hypoxia_55_date7 !=.
sort person_id HH7_60
by person_id: fillmissing HH7_60, with(first)
replace HH7_60 = 0 if HH7_60 ==. & hypoxia_55_date7 !=.
tab HH7_60 if MAP_amount ==1
count if hypoxia_55_date7 !=. & MAP_amount ==1