Wereman:
I think that, as soon as a formula starts to get complicated, especially if due to repetive parts, it is probably time to look for a VBA solution. Me, I'm hardheaded (persistant, I call it), and think VBA is too complicated for me. So, I try to obtain a formula type solution; if it seems out of the question, I just give up, and try method of presenting the problem. Let me give this a try, for your four teachers, each of whom teach two subjects.
Calling the teachers t1, t2, t3, and t4, and the subjects, d, a, m, and i, let's begin by forming some tables:
aa1=t1: ab1=d:ac1=a
aa2=t2: ab2=a:ac2=m
aa3=t3: ab3=m:ac1=i
aa4=t4: ab4=i:ac2=d
After merging the groups of two consecutive cells, the formula to use would be something like this, for a the subjects in two consecutive cells, say, in cells B4 and B5:
=if(or(and(B4=$ab$1,B5=$ac$1),and(B4=$ab$2,B5=$ac$2),and(B4=$ab$3,B5=$ac$3),$aa$4,
if(or(and(B4=$ab$2,B5=$ac$2),and(B4=$ab$3,B5=$ac$3),and(B4=$ab$4,B5=$ac$4),$aa$1,
if(or(and(B4=$ab$3,B5=$ac$3),and(B4=$ab$4,B5=$ac$4),and(B4=$ab$1,B5=$ac$1),$aa$2,
if(or(and(B4=$ab$4,B5=$ac$4),and(B4=$ab$1,B5=$ac$1),andB4=$ab$2,B5=$ac$2),$aa$3,""))))
Note that one builds up the formula, writing the first and(), copying it three times, and overwriting what is necessary, then copying the first IF four times, and proceeding to overwrite the old values that change, which is fairly easy. Now, one can copy this formula across, in the merged cells. Done