"e.g. columns of data from searchresult2 for filename15 get added into, and written into filename16"
That's because you dont have clear searchresult2 statement between the lines where filename15 and filename16 are being used. If the IF statement is true for both cases then filename15 and filename16 will have the same searhresult2
It would help if you can tell more, like, where are your calculating the searchresult2. Are your iterations based on limit2 variable?